package com.techsoul.module.accounting.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.accounting.enmus.AccountingStatusEnum;
import com.techsoul.module.accounting.enmus.DiscountActivityTypeEnum;
import com.techsoul.module.accounting.mapper.AccMyAccountTransactionMapper;
import com.techsoul.module.accounting.mapper.AccountingApMapper;
import com.techsoul.module.accounting.mapper.AccountingArMapper;
import com.techsoul.module.accounting.mapper.MaterialBuyPriceMapper;
import com.techsoul.module.accounting.pojo.entity.AccMyAccountTransaction;
import com.techsoul.module.accounting.pojo.entity.AccountingAp;
import com.techsoul.module.accounting.pojo.entity.AccountingAr;
import com.techsoul.module.accounting.pojo.entity.MaterialBuyPrice;
import com.techsoul.module.accounting.pojo.param.*;
import com.techsoul.module.accounting.pojo.vo.*;
import com.techsoul.module.accounting.service.IAccountingApService;
import com.techsoul.module.accounting.service.IMaterialBuyPriceService;
import com.techsoul.module.accounting.service.IPromotionDiscountPriceService;
import com.techsoul.module.basic.mapper.StoreMapper;
import com.techsoul.module.basic.pojo.entity.Store;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.pojo.vo.StoreVo;
import com.techsoul.module.goods.mapper.SpuMapper;
import com.techsoul.module.goods.pojo.entity.Spu;
import com.techsoul.module.goods.pojo.vo.SpuVo;
import com.techsoul.module.order.enmus.ReturnOrderStatusEnum;
import com.techsoul.module.order.enmus.SalesOrderSourceEnum;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.enmus.SalesOrderTypeEnum;
import com.techsoul.module.order.mapper.PriceTrackMapper;
import com.techsoul.module.order.mapper.ReturnOrderItemMapper;
import com.techsoul.module.order.mapper.SalesOrderItemMapper;
import com.techsoul.module.order.mapper.SalesOrderMapper;
import com.techsoul.module.order.pojo.entity.PriceTrack;
import com.techsoul.module.order.pojo.entity.ReturnOrderItem;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.entity.SalesOrderItem;
import com.techsoul.module.order.pojo.param.ReturnOrderItemSearchParam;
import com.techsoul.module.order.pojo.param.SalesOrderItemSaveParam;
import com.techsoul.module.order.pojo.param.SalesOrderItemSearchParam;
import com.techsoul.module.order.pojo.vo.*;
import com.techsoul.module.order.service.ISalesOrderItemService;
import com.techsoul.module.pms.mapper.CustGoodsMapMapper;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.pms.pojo.vo.CustGoodsMapVo;
import com.techsoul.module.goods.pojo.vo.SkuVo;
import com.techsoul.module.system.enmus.ErrorType;
import com.techsoul.module.system.mapper.OperationLogMapper;
import com.techsoul.module.system.pojo.entity.OperationLog;
import com.techsoul.module.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import  com.techsoul.module.accounting.pojo.vo.AccountingApViewVo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 财务应付 Service实现
 *
 * @author liuen
 * @date 2021-04-11
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class AccountingApServiceImpl implements IAccountingApService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private AccountingApMapper mapper;
    @Autowired
    private AccountingArMapper accountingArMapper;
    @Autowired
    private ReturnOrderItemMapper returnOrderItemMapper;
    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private SalesOrderItemMapper salesOrderItemmapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private IMaterialBuyPriceService materialBuyPriceService;
    @Autowired
    private IPromotionDiscountPriceService PromotionDiscountPriceService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PriceTrackMapper priceTrackmapper;

    @Autowired
    private SalesOrderMapper orderMapper;
    @Autowired
    private ISalesOrderItemService salesOrderItemService;
    @Autowired
    private CustGoodsMapMapper custGoodsMapMapper;
    @Autowired
    private IConfigService configService;

    @Autowired
    private MaterialBuyPriceMapper materialBuyPriceMapper;

    @Autowired
    private AccMyAccountTransactionMapper accMyAccountTransactionMapper;
    /**
     * 新增
     *
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(AccountingApSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccountingAp entity = new AccountingAp();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 去重
     */
    @Transactional(readOnly = false)
    @Override
    public void distinct() {
        // 查询重复的source_item_id、cust_sku_id
        List<Map<String, String>> dupData = this.mapper.findDistinct();
        // 删除同一source_item_id、cust_sku_id下的重复数据
        if (ListUtils.isNotEmpty(dupData)) {
            for (Map<String, String> map : dupData) {
                // 查询数据
                String sourceItemId = map.get("sourceItemId");
                String custSkuId = map.get("custSkuId");
                AccountingApSearchParam searchParam = new AccountingApSearchParam();
                searchParam.setSourceItemId(sourceItemId)
                        .setCustSkuId(custSkuId);
                List<AccountingApVo> apVoList = this.findAll(searchParam);
                // 保留一个id
                List<String> idList = apVoList.stream().map(AccountingApVo::getId).collect(Collectors.toList());
                idList.remove(0);
                // 删除其余的数据
                this.batchDelete(idList);
            }
        }
    }

    /**
     * 修改
     *
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(AccountingApSaveParam params) {
        AccountingAp entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public AccountingApVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    @Override
    public List<AccountingApVo> findAll(AccountingApSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     *
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccountingApVo> findAll(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }
    @Override
    public IPage<AccountingApVo> findAllWithRt(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAllWithRt(new Page<>(current, pageSize), params);
    }

    /**
     * 报表-分页
     *
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccountingApVo> settlementViewMonthly(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.settlementViewMonthly(new Page<>(current, pageSize), params);
    }

    /**
     * 采购报表-分页
     *
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccountingApVo> settlementViewSkuMonthly(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.settlementViewSkuMonthly(new Page<>(current, pageSize), params);
    }
    /**
     * 列表字段汇总
     *
     * @param params
     * @return
     */
    @Override
    public AccountingApVo sum(AccountingApSearchParam params) {
        return this.mapper.sum(params);
    }
    /**
     * 退单列表字段汇总
     *
     * @param params
     * @return
     */
    @Override
    public AccountingApVo returnSum(AccountingApSearchParam params) {
        return this.mapper.returnSum(params);
    }

    /**
     * 报表字段汇总
     *
     * @param params
     * @return
     */
    @Override
    public AccountingApVo settlementViewMonthlySum(AccountingApSearchParam params) {
        return this.mapper.settlementViewMonthlySum(params);
    }
    /**
     * 报表字段汇总
     *
     * @param params
     * @return
     */
    @Override
    public AccountingApVo settlementViewMonthlyReturnSum(AccountingApSearchParam params) {
        return this.mapper.settlementViewMonthlyReturnSum(params);
    }

    /**
     * 供应商列表-分页
     *
     * @param params
     *
     * @return
     */
    @Override
    public  IPage<AccountingApVo> supplierSumPage(AccountingApSearchParam params, Integer current, Integer pageSize) {
        //UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        return this.mapper.supplierSumPage(new Page<>(current, pageSize), params);
    }
    /**
     * 编辑价格
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String editPrice(AccountingApSaveParam params){

        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        AccountingApVo accountingAp = this.findById(params.getId());
        accountingAp.setAmount(params.getAmount()); // 付出去的 收款人
        accountingAp.setAmtGenAr(params.getAmtGenAr());
        accountingAp.setRate(params.getRate());
        accountingAp.setContractAmount(params.getContractAmount());
        AccountingAp entityFromDb = new AccountingAp();
        BeanUtils.copyProperties(accountingAp, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        this.mapper.updateById(entityFromDb);
        return "success";
    }
    /**
     * 产生财务结算数据
     *
     * @param salesOrderItem
     * @param materialBuyPriceSearchParam
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Double getBuyTotalAmount(SalesOrderItemVo salesOrderItem, MaterialBuyPriceSearchParam materialBuyPriceSearchParam) {
        materialBuyPriceSearchParam.setWholeSaleQuantity(salesOrderItem.getQty());
        List<MaterialBuyPriceVo> materialBuyPrices = materialBuyPriceService.findAll(materialBuyPriceSearchParam);
        if (materialBuyPrices != null && materialBuyPrices.size() > 0) {
            MaterialBuyPriceVo materialBuyPriceVo = materialBuyPrices.get(0);
            if(!StringUtils.isNull(materialBuyPriceVo.getSettlePrice())) {
                Double apamt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getSettlePrice()),salesOrderItem.getQty());
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
                salesOrderItem.setGenAccFailedReason("");
                salesOrderItem.setPrice(Double.valueOf(materialBuyPriceVo.getSettlePrice()));
                if(!StringUtils.isNull(materialBuyPriceVo.getCustRelSalesPrice())){
                    //   Double aramt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice()),salesOrderItem.getQty());
                    salesOrderItem.setAmtGenAr(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice())) ;// 与营销委结算价
                }
                return apamt;
            }else
                return 0.0;

        } else {
            if(!StringUtils.isNull(materialBuyPriceSearchParam.getCsaSpuCode())){
                materialBuyPriceSearchParam.setCsaSkuCode("通用");
                materialBuyPriceSearchParam.setMaterialMapId(null);
                materialBuyPrices = materialBuyPriceService.findAll(materialBuyPriceSearchParam);
                MaterialBuyPriceVo materialBuyPriceVo = null;
                if (materialBuyPrices != null && materialBuyPrices.size() > 0) {
                    materialBuyPriceVo = materialBuyPrices.get(0);
                    if(!StringUtils.isNull(materialBuyPriceVo.getSettlePrice())) {
                        Double apamt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getSettlePrice()),salesOrderItem.getQty());
                        salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
                        salesOrderItem.setGenAccFailedReason("");
                        if(!StringUtils.isNull(materialBuyPriceVo.getCustRelSalesPrice())){
                            //  Double aramt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice()),salesOrderItem.getQty());
                            salesOrderItem.setAmtGenAr(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice())) ;// 与营销委结算价
                        }
                        salesOrderItem.setPrice(Double.valueOf(materialBuyPriceVo.getSettlePrice()));
                        return apamt;
                    }else
                        return 0.0;

                }else{

                    salesOrderItem.setErrorCode("203");
                    String msg = "203-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo())
                            .concat(salesOrderItem.getCustSpuId()).concat("无法找到常规价格。");
                    salesOrderItem.setGenAccFailedReason(msg);

                    salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                    return 0.0;
                }
            }
            else{
                salesOrderItem.setErrorCode("203");
                String msg = "203-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo())
                        .concat(salesOrderItem.getCustSpuId()).concat("无法找到常规价格。");
                salesOrderItem.setGenAccFailedReason(msg);
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                return 0.0;
            }
        }

    }

    /**
     * 产生搞活动财务结算数据
     *
     * @param salesOrderItem
     * @param promotionDiscountPriceSearchParam
     * @return
     */
    @Override
    public Double getBuyTotalDisctAmount(SalesOrderItemVo salesOrderItem, PromotionDiscountPriceSearchParam promotionDiscountPriceSearchParam, MaterialBuyPriceSearchParam materialBuyPriceSearchParam) {
        promotionDiscountPriceSearchParam.setWholeSaleQuantity(salesOrderItem.getQty());
        double amt = 0.0;
        PromotionDiscountPriceVo promotionDiscountPrice =null;
        //promotionDiscountPriceSearchParam.setActType("!");
        List<PromotionDiscountPriceVo> promotionDiscountPrices = PromotionDiscountPriceService.findAll(promotionDiscountPriceSearchParam);
        if (promotionDiscountPrices != null && promotionDiscountPrices.size() > 0) { // 以SKU 查询 获得数据
            if(promotionDiscountPrices.size()>1){
                salesOrderItem.setErrorCode("1001");
                promotionDiscountPrice = promotionDiscountPrices.get(0);
                Double nowamt = Double.valueOf(promotionDiscountPrice.getSettlePrice());
                for(int i = 0; i<promotionDiscountPrices.size();i++){
                    PromotionDiscountPriceVo nextpromotionDiscountPriceVo
                            = (PromotionDiscountPriceVo)promotionDiscountPrices.get(i);
                    if(Double.valueOf(nextpromotionDiscountPriceVo.getSettlePrice())<nowamt){
                        nowamt = Double.valueOf(nextpromotionDiscountPriceVo.getSettlePrice());
                        promotionDiscountPrice = nextpromotionDiscountPriceVo;
                    }
                }

                salesOrderItem.setGenAccFailedReason("供应商相同商品在同一时间内登记了多个活动，取最低价格结算");
                //
            }else {
                promotionDiscountPrice = promotionDiscountPrices.get(0);
                salesOrderItem.setActType(promotionDiscountPrice.getActType());
                amt = NumberUtils.mul(salesOrderItem.getQty(), Double.valueOf(promotionDiscountPrice.getSettlePrice()).doubleValue());
            }

            salesOrderItem.setActType(promotionDiscountPrice.getActType());
            if (!StringUtils.isNull(promotionDiscountPrice.getActivityType())) {
                if (promotionDiscountPrice.getActivityType().equals(DiscountActivityTypeEnum.BF.getStatusCode())) {
                    Integer buyqty = promotionDiscountPrice.getBuyNumber();
                    Integer freeqty = promotionDiscountPrice.getGetFree();
                    Double totalQty = NumberUtils.add(buyqty, freeqty);
                    Double paypecentage = NumberUtils.div(buyqty, totalQty);
                    Double needPayQty = NumberUtils.mul(paypecentage, salesOrderItem.getQty());
                    double needPay = Math.ceil(needPayQty);
                    amt = NumberUtils.mul(needPay, Double.valueOf(promotionDiscountPrice.getSettlePrice()).doubleValue());
                } else if (promotionDiscountPrice.getActivityType().equals(DiscountActivityTypeEnum.BP.getStatusCode())) {
                    amt = NumberUtils.mul(salesOrderItem.getQty(), Double.valueOf(promotionDiscountPrice.getSettlePrice()).doubleValue());

                } else {
                    materialBuyPriceSearchParam.setWholeSaleQuantity(salesOrderItem.getQty());
                    List<MaterialBuyPriceVo> materialBuyPrices = materialBuyPriceService.findAll(materialBuyPriceSearchParam);
                    if (materialBuyPrices != null && materialBuyPrices.size() > 0) {
                        if (promotionDiscountPrice.getActivityType().equals(DiscountActivityTypeEnum.PT.getStatusCode())) {
                            MaterialBuyPriceVo materialBuyPriceVo = materialBuyPrices.get(0);
                            if(!StringUtils.isNull(materialBuyPriceVo.getSettlePrice())) {
                                BigDecimal apamt =new BigDecimal(Double.valueOf(materialBuyPriceVo.getSettlePrice())) ;
                                amt = NumberUtils.mul(apamt.doubleValue(), promotionDiscountPrice.getPromotionDiscountRate().doubleValue());
                            }
                        } else if (promotionDiscountPrice.getActivityType().equals(DiscountActivityTypeEnum.DP.getStatusCode())) {
                            MaterialBuyPriceVo materialBuyPriceVo = materialBuyPrices.get(0);
                            if(!StringUtils.isNull(materialBuyPriceVo.getSettlePrice())) {
                                BigDecimal apamt = new BigDecimal(Double.valueOf(materialBuyPriceVo.getSettlePrice())) ;
                                amt = NumberUtils.sub(apamt.doubleValue(), Double.valueOf(promotionDiscountPrice.getSettlePrice()).doubleValue());
                            }
                        }
                    } //end if
                    else{
                        salesOrderItem.setGenAccFailedReason("活动折扣方案没有查到-无法匹配常规格");
                        salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                        return 0.0;
                    }
                } //end else
            } // end if
        }// end if
        else{
            salesOrderItem.setGenAccFailedReason("活动折扣方案没有查到-无法匹配价格");
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            return 0.0;
        }

        if(!StringUtils.isNull(promotionDiscountPrice.getCustRelSalesPrice())){
            //   Double aramt =NumberUtils.mul(Double.valueOf(promotionDiscountPrice.getCustRelSalesPrice()),salesOrderItem.getQty());
            salesOrderItem.setAmtGenAr(Double.valueOf(promotionDiscountPrice.getCustRelSalesPrice())) ;// 与营销委结算价
        }
        salesOrderItem.setPrice(Double.valueOf(promotionDiscountPrice.getSettlePrice()));
        salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
        salesOrderItem.setGenAccFailedReason("");
        return amt;
    }
    /**
     * 产生搞活动财务结算数据并计算折扣后价格
     *
     * @param salesOrderItem
     * @param promotionDiscountPriceSearchParam
     * @return
     */
    @Override
    public Double getBuyTotalCuponAmount(SalesOrderItemVo salesOrderItem, PromotionDiscountPriceSearchParam promotionDiscountPriceSearchParam, MaterialBuyPriceSearchParam materialBuyPriceSearchParam) {
        promotionDiscountPriceSearchParam.setWholeSaleQuantity(salesOrderItem.getQty());
        double amt = 0.0;
        double rtAmt = 0.0;
        PromotionDiscountPriceVo promotionDiscountPrice = null;
        //promotionDiscountPriceSearchParam.setActType("领券");
        List<PromotionDiscountPriceVo> promotionDiscountPrices = PromotionDiscountPriceService.findAll(promotionDiscountPriceSearchParam);
        if (promotionDiscountPrices != null && promotionDiscountPrices.size() > 0) { // 以SKU 查询 获得数据
            if(promotionDiscountPrices.size()>1){
                //   salesOrderItem.setErrorCode("1001");
                promotionDiscountPrice = promotionDiscountPrices.get(0);
                Double nowamt = Double.valueOf(promotionDiscountPrice.getSettlePrice());
                for(int i = 0; i<promotionDiscountPrices.size();i++){
                    PromotionDiscountPriceVo nextpromotionDiscountPriceVo
                            = (PromotionDiscountPriceVo)promotionDiscountPrices.get(i);
                    if(Double.valueOf(nextpromotionDiscountPriceVo.getSettlePrice())<nowamt){
                        nowamt = Double.valueOf(nextpromotionDiscountPriceVo.getSettlePrice());
                    }
                    amt = nowamt;
                }

                salesOrderItem.setGenAccFailedReason("供应商相同商品在同一时间内登记了多个活动，取最低价格结算");
                //
            }else {
                promotionDiscountPrice = promotionDiscountPrices.get(0);
                salesOrderItem.setActType(promotionDiscountPrice.getActType());
                amt = NumberUtils.mul(salesOrderItem.getQty(), Double.valueOf(promotionDiscountPrice.getSettlePrice()).doubleValue());
            }


        } // end if
        else{
            //
            //salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            if(salesOrderItem.getCustRelSalesUnitPrice()!=null){
                Double custRelSalesPrice = NumberUtils.mul(salesOrderItem.getCustRelSalesUnitPrice(),salesOrderItem.getQty());
                if(salesOrderItem.getStoreDiscountAmt()!=null){
                    custRelSalesPrice = NumberUtils.sub(custRelSalesPrice,salesOrderItem.getStoreDiscountAmt());

                }
                if(salesOrderItem.getStoreDiscountAmtPoint()!=null){
                    Double relamt= NumberUtils.mul(salesOrderItem.getStoreDiscountAmtPoint(),0.05);
                    custRelSalesPrice = NumberUtils.sub(custRelSalesPrice,relamt);

                }
                salesOrderItem.setCustRelSalesPrice(String.valueOf(custRelSalesPrice));
                //     salesOrderItem.setGenAccFailedReason("领券价格没有查到-无法匹配规格");
            }

            return 0.0;
        }

        if(!StringUtils.isNull(promotionDiscountPrice.getCustRelSalesPrice())){
            // Double aramt =NumberUtils.mul(Double.valueOf(promotionDiscountPrice.getCustRelSalesPrice()),salesOrderItem.getQty());
            salesOrderItem.setAmtGenAr(Double.valueOf(promotionDiscountPrice.getCustRelSalesPrice())) ;// 与营销委结算价
        }
        // salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
        return amt;
    }

    @Transactional(readOnly = false)
    @Override
    public String handleConfirmPay(String id,UserVo userVo){

        String rt = "success";
        AccountingAp accountingAp = this.mapper.selectById(id);
        accountingAp.setStatus(AccountingStatusEnum.CONFIRMED.getStatus());
        AccMyAccountTransaction accMyAccountTransaction = new AccMyAccountTransaction();
        accMyAccountTransaction.setTranscationAmount(accountingAp.getAmount());

        accMyAccountTransaction.setCompanyName(accountingAp.getStoreName());
        accMyAccountTransaction.setCompanyId(accountingAp.getPayCust());

        accMyAccountTransaction.setPaymentOrIncome("payment");
        accMyAccountTransaction.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accMyAccountTransaction.setTranscationPartnerId(accountingAp.getBillToCust());
        accMyAccountTransaction.setTranscationPartnerName(accountingAp.getBillToCustName());
        accMyAccountTransaction.setTranscationTime(new Date());

        accMyAccountTransaction.setId(idWorker.nextId() + "").preInsert(userVo.getId());

        AccMyAccountTransaction accMyAccountTransactionAr = null;
        if(accountingAp.getSettlementId()!=null&&accountingAp.getSettlementId()!=""){
            AccountingAr accountingAr = this.accountingArMapper.selectById(accountingAp.getSettlementId());
            accountingAr.setStatus(AccountingStatusEnum.CONFIRMED.getStatus());

            accountingAr.preUpdate(userVo.getId());
            this.accountingArMapper.updateById(accountingAr);
            accMyAccountTransactionAr = new AccMyAccountTransaction();
            accMyAccountTransactionAr.setTranscationAmount(accountingAr.getAmount());
            accMyAccountTransactionAr.setCompanyName(accountingAr.getShipperName());
            accMyAccountTransactionAr.setCompanyId(accountingAr.getPayCust());
            accMyAccountTransactionAr.setPaymentOrIncome("income");
            accMyAccountTransactionAr.setStatus(AccountingStatusEnum.CREATED.getStatus());
            accMyAccountTransactionAr.setTranscationPartnerId(accountingAr.getBillToCust());
            accMyAccountTransactionAr.setTranscationPartnerName(accountingAr.getBillToCustName());

            accMyAccountTransaction.setTranscationTime(new Date());
            accMyAccountTransactionAr.setId(idWorker.nextId() + "").preInsert(userVo.getId());

        }
        accountingAp.preUpdate(userVo.getId());
        this.mapper.updateById(accountingAp);
        this.accMyAccountTransactionMapper.insert(accMyAccountTransaction);
        if(accMyAccountTransactionAr!=null){
            this.accMyAccountTransactionMapper.insert(accMyAccountTransactionAr);
        }

        return rt;
    }
    @Transactional(readOnly = false)
    @Override
    public String settleAgain(String id,UserVo userVo){

        String rt = "success";
        SalesOrderItem neeagain = this.salesOrderItemmapper.findEntityById(id);
        if(!StringUtils.isNull(neeagain.getErrorCode())){
            if(neeagain.getErrorCode().equals("601")){
                StoreVo store = storeMapper.findByCode(neeagain.getStoreId());
                if(store!=null) {
                    neeagain.setSupplierNo(store.getSupplierId());
                    neeagain.setSupplierName(store.getSupplierName());
                    neeagain.setStoreName(store.getStoreName());
                    neeagain.setErrorCode("");
                    neeagain.setGenAccFailedReason("");
                    this.salesOrderItemmapper.updateById(neeagain);
                }else{
                    return "店铺不在本系统";
                }
            }
        }
        SalesOrderItemVo itemVo = this.salesOrderItemmapper.findById(id);
        rt = this.getSupplierApAmount(itemVo,userVo);
        return rt;
    }


    @Transactional(readOnly = false)
    @Override
    public String batchGenerateHistoricArAp(List<String> idList,UserVo userVo){

        String rt = "success";

        for(int i = 0; i < idList.size(); i++){
            String itemid = (String)idList.get(i);
            SalesOrderItemVo salesOrderItemVo =this.salesOrderItemmapper.findById(itemid);
            if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
                salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
                this.genOperationLog(salesOrderItemVo,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
                this.salesOrderItemService.update(salesOrderItemVo.getId(), salesOrderItemSaveParam);
                continue;
            }
            rt = this.getCustomerArAmount(salesOrderItemVo,userVo);
        }
        return rt;
    }
    @Transactional(readOnly = false)
    @Override
    public String batchGenerateArAp(List<String> idList,UserVo userVo){

        String rt = "success";

        for(int i = 0; i < idList.size(); i++){
            String itemid = (String)idList.get(i);
            SalesOrderItemVo salesOrderItemVo =this.salesOrderItemmapper.findById(itemid);
            if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
                salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
                this.genOperationLog(salesOrderItemVo,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
                this.salesOrderItemService.update(salesOrderItemVo.getId(), salesOrderItemSaveParam);
                continue;
            }
            rt = this.getSupplierApAmount(salesOrderItemVo,userVo);
        }
        return rt;
    }

    @Override
    public List<AccountingApVo> suppierViewAccount(String supplierNo,String dateFrom,String dateTo){
        if(StringUtils.isNull(dateTo)){
            return this.mapper.suppierViewAccountDateFrom(supplierNo, dateFrom);
        }  else if(StringUtils.isNull(dateFrom)){
            return this.mapper.suppierViewAccountDateTo(supplierNo, dateTo);
        }else if(dateFrom.equals(dateFrom)) {
            return this.mapper.suppierViewAccount(supplierNo, dateFrom);
        }
        else{
            return this.mapper.suppierViewAccountBetween(supplierNo, dateFrom,dateTo);
        }

    }

    @Transactional(readOnly = false)
    @Override
    public void generateMigrationArAp(UserVo userVo){
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        salesOrderItemSearchParam.setErrorFlag("N");
        List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        for(int i = 0; i < notSettlements.size(); i++){
            SalesOrderItemVo salesOrderItemVo =(SalesOrderItemVo)notSettlements.get(i);
            if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
                salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
                this.genOperationLog(salesOrderItemVo,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
                this.salesOrderItemService.update(salesOrderItemVo.getId(), salesOrderItemSaveParam);
                continue;
            }
            this.getCustomerArAmount(salesOrderItemVo,userVo);
        }
    }

//    @Transactional(readOnly = false)
//    @Override
//    public void generateMigrationArAp(UserVo userVo){
//        AsyncManager.me().execute(AccountingApAsyncFactory.asyncGenerateMigrationArAp(userVo));
//    }

    @Transactional(readOnly = false)
    @Override
    public void asyncGenerateMigrationArAp(UserVo userVo){
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        salesOrderItemSearchParam.setErrorFlag("N");
        List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        for(int i = 0; i < notSettlements.size(); i++){
            SalesOrderItemVo salesOrderItemVo =(SalesOrderItemVo)notSettlements.get(i);
            if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
                salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
                this.genOperationLog(salesOrderItemVo,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItemVo.getId(), salesOrderItemSaveParam,userVo);
                continue;
            }
            this.getCustomerArAmount(salesOrderItemVo,userVo);
        }
    }
    @Transactional(readOnly = false)
    @Override
    public String fixDataFour(UserVo userVo) {
        ReturnOrderItemSearchParam searchParam = new ReturnOrderItemSearchParam();
        searchParam.setLastUpdDt("2021-1");
        List<ReturnOrderItemVo> needFix = this.returnOrderItemMapper.findAll(searchParam);
        Pattern p =null;
        Matcher m = null;;
        String rt = "";
        for (int i = 0; i < needFix.size(); i++) {
            ReturnOrderItemVo returnOrderItemVo = (ReturnOrderItemVo)needFix.get(i);
            String itemno = returnOrderItemVo.getCustSalesOrderItemNo();
            String spu = returnOrderItemVo.getCustSpuId();
            String sku = returnOrderItemVo.getCustSkuId();
            if(!StringUtils.isNull(returnOrderItemVo.getCustSpuId())) {
                p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(spu);
                spu = m.replaceAll("");
            }
            if(!StringUtils.isNull(returnOrderItemVo.getCustSkuId())) {
                p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(sku);
                sku = m.replaceAll("");

            }
            if(!StringUtils.isNull(returnOrderItemVo.getCustSalesOrderItemNo())) {
                p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(itemno);
                itemno = m.replaceAll("");

            }
            List<AccountingAp> accountingAps =
                    this.mapper.findByCustSalesOrderItemNoAndOrProductSkuCode(itemno,sku,spu);
            if(accountingAps!=null&&accountingAps.size()>0){
                AccountingAp accountingAp = (AccountingAp)accountingAps.get(0);
                if(accountingAp.getRate()!=null&&accountingAp.getReturnQty()!=null){
                    Double rtamt = NumberUtils.mul(accountingAp.getRate().doubleValue(),accountingAp.getReturnQty().doubleValue());
                    accountingAp.setBuyReturnAmt(rtamt);

                }


                AccountingAp entityFromDb = new AccountingAp();

                BeanUtils.copyProperties(accountingAp, entityFromDb);
                entityFromDb.preUpdate(userVo.getId());
                this.mapper.updateById(entityFromDb);
            }

        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String fixDataThree(UserVo userVo) {
        ReturnOrderItemSearchParam searchParam = new ReturnOrderItemSearchParam();
        searchParam.setLastUpdDt("2021-1");
        List<ReturnOrderItemVo> needFix = this.returnOrderItemMapper.findAll(searchParam);
        Pattern p =null;
        Matcher m = null;;
        String rt = "";
        for (int i = 0; i < needFix.size(); i++) {
            ReturnOrderItemVo returnOrderItemVo = (ReturnOrderItemVo)needFix.get(i);
         /*   if(!StringUtils.isNull(returnOrderItemVo.getLastUpdDt())){
                if(!returnOrderItemVo.getLastUpdDt().contains(" ")){
                    String ret = returnOrderItemVo.getLastUpdDt();
                    String firsthalfret = returnOrderItemVo.getLastUpdDt().substring(0,9);
                    String sec =returnOrderItemVo.getLastUpdDt().substring(10);
                    String finalstr = firsthalfret.concat(" ").concat(sec);
                    returnOrderItemVo.setLastUpdDt(finalstr);
                    ReturnOrderItem entityFromDb = new ReturnOrderItem();

                    BeanUtils.copyProperties(returnOrderItemVo, entityFromDb);
                    entityFromDb.preUpdate(userVo.getId());
                    this.returnOrderItemMapper.updateById(entityFromDb);
                }
            }*/

            String itemno = returnOrderItemVo.getCustSalesOrderItemNo();
            String spu = returnOrderItemVo.getCustSpuId();
            String sku = returnOrderItemVo.getCustSkuId();
            if(!StringUtils.isNull(returnOrderItemVo.getCustSpuId())) {
                p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(spu);
                spu = m.replaceAll("");
            }
            if(!StringUtils.isNull(returnOrderItemVo.getCustSkuId())) {
                p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(sku);
                sku = m.replaceAll("");

            }
            if(!StringUtils.isNull(returnOrderItemVo.getCustSalesOrderItemNo())) {
                p = Pattern.compile("\\s*|\t|\r|\n");
                m = p.matcher(itemno);
                itemno = m.replaceAll("");

            }
            List<AccountingAp> accountingAps =
                    this.mapper.findByCustSalesOrderItemNoAndOrProductSkuCode(itemno,sku,spu);
            if(accountingAps!=null&&accountingAps.size()>0){
                AccountingAp accountingAp = (AccountingAp)accountingAps.get(0);
                if(!StringUtils.isNull(returnOrderItemVo.getLastUpdDt())){
                    accountingAp.setReturnTime(DateUtils.parseDate(returnOrderItemVo.getLastUpdDt()));
                    p = Pattern.compile("\\s*|\t|\r|\n");
                    String updttime = returnOrderItemVo.getLastUpdDt();
                    m = p.matcher(updttime);
                    updttime = m.replaceAll("");
                    String retDate =updttime.substring(0,7);
                    accountingAp.setReturnMonthYearDate(retDate);
                }


                AccountingAp entityFromDb = new AccountingAp();

                BeanUtils.copyProperties(accountingAp, entityFromDb);
                entityFromDb.preUpdate(userVo.getId());
                this.mapper.updateById(entityFromDb);
            }

        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String fixDataTwo(UserVo userVo) {
        AccountingApSearchParam searchParam = new AccountingApSearchParam();
        searchParam.setStatus(AccountingStatusEnum.needFix.getStatus());
        List<AccountingApVo> needFix = this.mapper.findAll(searchParam);
        for (int i = 0; i < needFix.size(); i++) {
            AccountingApVo accountingAp = (AccountingApVo)needFix.get(i);

            Store store = this.storeMapper.findStoreByCode(accountingAp.getStoreId());
            if(store!=null){
                accountingAp.setStoreName(store.getStoreName());
                accountingAp.setPayCust(store.getSupplierId()); // 付出去的 收款人
                accountingAp.setShipperName(store.getSupplierName());
                accountingAp.setOriginalCustName(store.getSupplierName());
                accountingAp.setStatus(AccountingStatusEnum.CREATED.getEventCode());
                AccountingAp entityFromDb = new AccountingAp();

                BeanUtils.copyProperties(accountingAp, entityFromDb);
                entityFromDb.preUpdate(userVo.getId());
                this.mapper.updateById(entityFromDb);
            }

        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String fixData(UserVo userVo) {
        AccountingApSearchParam searchParam = new AccountingApSearchParam();
        searchParam.setStatus(AccountingStatusEnum.needFix.getStatus());
        List<AccountingApVo> needFix = this.mapper.findAll(searchParam);
        for (int i = 0; i < needFix.size(); i++) {
            AccountingApVo accountingAp = (AccountingApVo)needFix.get(i);
            if(StringUtils.isNull(accountingAp.getPayCust())){
                Store store = this.storeMapper.findStoreByCode(accountingAp.getStoreId());
                if(store!=null){
                    accountingAp.setPayCust(store.getSupplierId()); // 付出去的 收款人
                    accountingAp.setShipperName(store.getSupplierName());
                    accountingAp.setOriginalCustName(store.getSupplierName());
                    accountingAp.setStatus(AccountingStatusEnum.needFix.getEventCode());
                    AccountingAp entityFromDb = new AccountingAp();

                    BeanUtils.copyProperties(accountingAp, entityFromDb);
                    entityFromDb.preUpdate(userVo.getId());
                    this.mapper.updateById(entityFromDb);
                }
            }
        }
        return "success";
    }

    @Transactional(readOnly = false)
    @Override
    public void regenerateArAp(UserVo userVo,SalesOrderItemVo salesOrderItemVo){
        //   SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        //   salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());

        //   String rt = "success";
        //   List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        //   for(int i = 0; i < notSettlements.size(); i++){
        //    SalesOrderItemVo salesOrderItemVo =(SalesOrderItemVo)notSettlements.get(i);
        if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
            salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
            this.genOperationLog(salesOrderItemVo,userVo);
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
            salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
            this.salesOrderItemService.update(salesOrderItemVo.getId(), salesOrderItemSaveParam);
            return;
        }
        this.getSupplierApAmount(salesOrderItemVo,userVo);
        // }
    }
    @Transactional(readOnly = false)
    @Override
    public void generateArAp(UserVo userVo,SalesOrderItemVo salesOrderItemVo){
        //   SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        //   salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        //   salesOrderItemSearchParam.setErrorFlag("N");
        //   String rt = "success";
        //   List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        //   for(int i = 0; i < notSettlements.size(); i++){
        //   SalesOrderItemVo salesOrderItemVo =(SalesOrderItemVo)notSettlements.get(i);
        if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
            salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
            this.genOperationLog(salesOrderItemVo,userVo);
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
            salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
            this.salesOrderItemService.update(salesOrderItemVo.getId(), salesOrderItemSaveParam);
            return;
        }
        this.getSupplierApAmount(salesOrderItemVo,userVo);
        //  }
    }

//    @Transactional(readOnly = false)
//    @Override
//    public void generateArAp(UserVo userVo){
//        AsyncManager.me().execute(AccountingApAsyncFactory.asyncGenerateArAp(userVo));
//    }

    @Transactional(readOnly = false)
    @Override
    public void asyncGenerateArAp(UserVo userVo){
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        salesOrderItemSearchParam.setErrorFlag("N");
        List<SalesOrderItemVo> notSettlements = this.salesOrderItemService.findAll(salesOrderItemSearchParam);
        for(int i = 0; i < notSettlements.size(); i++){
            SalesOrderItemVo salesOrderItemVo =(SalesOrderItemVo)notSettlements.get(i);
            if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
                salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
                this.genOperationLog(salesOrderItemVo,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItemVo.getId(), salesOrderItemSaveParam,userVo);
                continue;
            }
            this.getSupplierApAmount(salesOrderItemVo,userVo);
        }
    }

    @Transactional(readOnly = false)
    @Override
    public String batchGenerateArAp(String[] ids, UserVo userVo){

        return null;
    }
    @Transactional(readOnly = false)
    @Override
    public String generateSelectedArAp(SalesOrderItemVo  salesOrderItemVo ,UserVo userVo){
        String rt =   this.getSupplierApAmount(salesOrderItemVo,userVo);
        return rt;
    }
    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(SalesOrderItemVo data, UserVo user) {
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        operationLog.setErrorMsg(data.getImportErrorMesg());
        operationLog.setMethod(data.getErrorCode());
        operationLog.setLocation(data.getCustSalesOrderNo());
        operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }
    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(ReturnOrderItem data, UserVo user) {
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationType(ErrorType.RTORDERIMPORT.getStatusName());
        operationLog.setErrorMsg(data.getImportErrorMesg());
        operationLog.setMethod(data.getErrorCode());
        operationLog.setLocation(data.getCustSalesOrderNo());
        operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }

    /**
     * 获得供应商付款金额
     * @param salesOrderItem
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String getCustomerArAmount(SalesOrderItemVo  salesOrderItem,UserVo userVo){
        Double apamt = 0.0;
        String rt = "success";
        String itemErrorMsg = "结算生成：";
        String disctFlag = "N";


        Date today = new Date();


        MaterialBuyPriceSearchParam materialBuyPriceSearchParam = new MaterialBuyPriceSearchParam();




        if(apamt==0.0) {
            // 查正常活动
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();

            materialBuyPriceSearchParam.setMallCustNo(salesOrderItem.getCustomerNo());
            materialBuyPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));


            materialBuyPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());
            if(!StringUtils.isNull(salesOrderItem.getMaterialMapId())){
                materialBuyPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                if(apamt==0.0) {
                    materialBuyPriceSearchParam.setMaterialMapId(null);
                    materialBuyPriceSearchParam.setMaterialMapId(null);
                    materialBuyPriceSearchParam.setCsaSkuCode("通用");
                    materialBuyPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                    apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                }

            }else  if(!StringUtils.isNull(salesOrderItem.getGoodGroupId())){
                materialBuyPriceSearchParam.setGoodGroupId(salesOrderItem.getGoodGroupId());
                apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
            }

        }else{
            disctFlag = "Y";
        }


        if (!StringUtils.isNull(salesOrderItem.getStoreDiscountCode())
                &&salesOrderItem.getStoreDiscountCode()!="") {//搞活动
            Double storeDiscount = 0.0;
            String storedisctflag = "N";
            double storeCuponDisct = 0.0;
            if(salesOrderItem.getStoreDiscountAmt()!=null){
                storeDiscount = salesOrderItem.getStoreDiscountAmt();
                storeCuponDisct = NumberUtils.add(storeCuponDisct,storeDiscount);
                if(!StringUtils.isNull(salesOrderItem.getActivityName())){
                    if(salesOrderItem.getActivityName().contains("直播")||salesOrderItem.getActivityName().contains("秒杀"))
                        apamt = NumberUtils.sub(apamt,storeCuponDisct);
                }

                if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                    Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeCuponDisct);
                    salesOrderItem.setPayMoney(ar);
                }
                storedisctflag = "Y";
            }
            if(salesOrderItem.getStoreDiscountAmtPoint()!=null){
                storeDiscount = NumberUtils.mul(salesOrderItem.getStoreDiscountAmtPoint(),0.05);
                storeCuponDisct = NumberUtils.add(storeCuponDisct,storeDiscount);
                if(!StringUtils.isNull(salesOrderItem.getActivityName())){
                    if(salesOrderItem.getActivityName().contains("直播")||salesOrderItem.getActivityName().contains("秒杀"))
                        apamt = NumberUtils.sub(apamt,storeCuponDisct);
                }

                if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                    Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeCuponDisct);
                    salesOrderItem.setPayMoney(ar);
                }

                storedisctflag = "Y";
            }
        }


        SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
        salesOrderItem.setGenAccFailedReason("");
        salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
        salesOrderItem.setGenAccFailedReason("");
        BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
        this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
        String apgenerateResult = this.generateApList(apamt,salesOrderItem,userVo);
        return rt;


    }
    /**
     * 获得供应商付款金额
     * @param salesOrderItem
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String getSupplierApAmount(SalesOrderItemVo  salesOrderItem,UserVo userVo){
        Double apamt = 0.0;
        String rt = "success";
        // String salesOrderItemNo = (String) map.get("salesOrderItemNo");
        //  SalesOrderItemVo salesOrderItem = salesOrderItemService.findById(salesOrderItemNo);
        String itemErrorMsg = "结算生成：";
        String disctFlag = "N";
        if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
          /* if(salesOrderItem.getErrorCode().contains("601")){
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());

                String msg = "601-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat(salesOrderItem.getStoreId()).concat("。店铺数据没有维护 ");
                salesOrderItem.setGenAccFailedReason(msg);
                itemErrorMsg = "店铺数据没有维护";
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                return  itemErrorMsg;
            }*/
            if(salesOrderItem.getErrorCode().contains("101")){
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                String msg = "101-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("订单已经输入，不可重复输入结算 ");

                salesOrderItem.setGenAccFailedReason(msg);

                itemErrorMsg = "订单已经输入，不可重复输入结算";
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                return  itemErrorMsg;
            }
            if(salesOrderItem.getErrorCode().contains("601")) {
                Store settlestore = this.storeMapper.findStoreByCode(salesOrderItem.getStoreId());
                if (settlestore == null) {
                    salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());

                    String msg = "601-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                            .concat(salesOrderItem.getCustSpuId()).concat(salesOrderItem.getStoreId()).concat("。店铺数据没有维护 ");
                    salesOrderItem.setGenAccFailedReason(msg);
                    itemErrorMsg = "店铺数据没有维护";
                    SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                    salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                    BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                    this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam, userVo);
                    return itemErrorMsg;
                }
            }
        }
        if(StringUtils.isNull(salesOrderItem.getStoreId())){
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());

            String msg = "603-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                    .concat(salesOrderItem.getCustSpuId()).concat("。订单没有店铺数据 ");
            salesOrderItem.setGenAccFailedReason(msg);
            itemErrorMsg = "订单没有店铺数据";
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
            this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
            return  itemErrorMsg;
        }

        if(StringUtils.isNull(salesOrderItem.getMaterialMapId())){
            CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(salesOrderItem.getCustSpuId(),salesOrderItem.getCustSkuId(),salesOrderItem.getCustomerNo());
            if(custGoodsMapVo==null){
                custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(salesOrderItem.getCustSpuId(),"通用",salesOrderItem.getCustomerNo());
            }
            if(custGoodsMapVo==null){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                salesOrderItem.setErrorCode("201");


                String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("客户商品不存在本系统，请先导入商品 ");
                salesOrderItem.setGenAccFailedReason(msg);
                // this.genOperationLog(salesOrderItem,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderNo().concat(salesOrderItem.getImportErrorMesg()));
                return  itemErrorMsg;
            }else{
                salesOrderItem.setMaterialMapId(custGoodsMapVo.getId());
            }
        }else{
            CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findById(salesOrderItem.getMaterialMapId());
            if(custGoodsMapVo==null){
                custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(salesOrderItem.getCustSpuId(),salesOrderItem.getCustSkuId(),salesOrderItem.getCustomerNo());
                if(custGoodsMapVo==null) {
                    custGoodsMapVo = custGoodsMapMapper.findByCustGoodNoAndSkuNo(salesOrderItem.getCustSpuId(), "通用", salesOrderItem.getCustomerNo());
                }
            }
            if(custGoodsMapVo==null){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                salesOrderItem.setErrorCode("201");

                String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("客户商品不存在本系统，请先导入商品 ");
                salesOrderItem.setGenAccFailedReason(msg);
                // this.genOperationLog(salesOrderItem,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderNo().concat(salesOrderItem.getImportErrorMesg()));
                return  itemErrorMsg;
            }else{
                salesOrderItem.setMaterialMapId(custGoodsMapVo.getId());
            }
        }
        Date today = new Date();

        if(salesOrderItem.getCreateTime().after(today)){
            salesOrderItem.setErrorFlag("Y");
            salesOrderItem.setErrorCode("1002");
            String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                    .concat(salesOrderItem.getCustSpuId()).concat("订单日期大于当前时间，不可能出现，系统不予处理 ");
            salesOrderItem.setGenAccFailedReason(msg);
            // this.genOperationLog(salesOrderItem,userVo);
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
            this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
            itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderItemNo().concat(salesOrderItem.getImportErrorMesg()));
            return  itemErrorMsg;
        }
        if(salesOrderItem.getStoreDiscountAmtPoint()!=null&&salesOrderItem.getStoreDiscountAmtPoint()!=0.0){
            if(StringUtils.isNull(salesOrderItem.getStoreDiscountCode())){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setErrorCode("1003");
                String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("有领券金额，但没有券码，数据有问题，请联系营销委 ");
                salesOrderItem.setGenAccFailedReason(msg);
                // this.genOperationLog(salesOrderItem,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderItemNo().concat(salesOrderItem.getImportErrorMesg()));
                return  itemErrorMsg;
            }
        }
        if(salesOrderItem.getStoreDiscountAmt()!=null&&salesOrderItem.getStoreDiscountAmt()!=0.0){
            if(StringUtils.isNull(salesOrderItem.getStoreDiscountCode())){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setErrorCode("1004");
                String msg = salesOrderItem.getErrorCode().concat("订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("有领券金额，但没有券码，数据有问题，请联系营销委 ");
                salesOrderItem.setGenAccFailedReason(msg);
                // this.genOperationLog(salesOrderItem,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderNo().concat(salesOrderItem.getImportErrorMesg()));
                return  itemErrorMsg;
            }
        }
        if(!StringUtils.isNull(salesOrderItem.getStoreDiscountActId())
                &&salesOrderItem.getStoreDiscountActId()!=""){
            if(StringUtils.isNull(salesOrderItem.getStoreDiscountCode())){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setErrorCode("1004");
                String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("有领券活动ID ，没有领券券码 ");
                salesOrderItem.setGenAccFailedReason(msg);
                // this.genOperationLog(salesOrderItem,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderNo().concat(salesOrderItem.getImportErrorMesg()));
                return  itemErrorMsg;
            }
        }
        if(!StringUtils.isNull(salesOrderItem.getStoreDiscountCode())
                &&salesOrderItem.getStoreDiscountCode()!=""){
            if(StringUtils.isNull(salesOrderItem.getStoreDiscountActId())){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setErrorCode("1004");
                String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("有领券券码，没有领券活动ID ");
                salesOrderItem.setGenAccFailedReason(msg);
                // this.genOperationLog(salesOrderItem,userVo);
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                itemErrorMsg=itemErrorMsg.concat(salesOrderItem.getCustSalesOrderNo().concat(salesOrderItem.getImportErrorMesg()));
                return  itemErrorMsg;
            }
        }
        MaterialBuyPriceSearchParam materialBuyPriceSearchParam = new MaterialBuyPriceSearchParam();

        if (!StringUtils.isNull(salesOrderItem.getDiscountActivityCode())
                &&salesOrderItem.getDiscountActivityCode()!="") {//搞活动
            PromotionDiscountPriceSearchParam promotionDiscountPriceSearchParam
                    = new PromotionDiscountPriceSearchParam();
            promotionDiscountPriceSearchParam.setMallCustNo(salesOrderItem.getMallBuyerNo());
            promotionDiscountPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());
            promotionDiscountPriceSearchParam.setEffectUntilDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            promotionDiscountPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            materialBuyPriceSearchParam.setEffectUntilDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            materialBuyPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            materialBuyPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());

            if(!StringUtils.isNull(salesOrderItem.getMaterialMapId())){
                promotionDiscountPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                materialBuyPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                //  promotionDiscountPriceSearchParam.setActType("!");
                apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);
                if(apamt==0.0){
                    promotionDiscountPriceSearchParam.setMaterialMapId(null);
                    materialBuyPriceSearchParam.setMaterialMapId(null);
                    promotionDiscountPriceSearchParam.setCsaSkuCode("通用");
                    promotionDiscountPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                    // promotionDiscountPriceSearchParam.setActType("!");
                    apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);
                }
            }else if(!StringUtils.isNull(salesOrderItem.getGoodGroupId())){
                promotionDiscountPriceSearchParam.setGoodGroupId(salesOrderItem.getGoodGroupId());
                materialBuyPriceSearchParam.setGoodGroupId(salesOrderItem.getGoodGroupId());
                // promotionDiscountPriceSearchParam.setActType("!");
                apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);
            }else{
                promotionDiscountPriceSearchParam.setCsaSkuCode(salesOrderItem.getCustSkuId());
                promotionDiscountPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                // promotionDiscountPriceSearchParam.setActType("!");
                apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);
                if(apamt==0.0){
                    promotionDiscountPriceSearchParam.setCsaSkuCode("通用");
                    promotionDiscountPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                    //  promotionDiscountPriceSearchParam.setActType("!");
                    apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);

                }
            }


            if(apamt==0.0){
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
                if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                    salesOrderItem.setErrorFlag("Y");
                    String msg = salesOrderItem.getErrorCode().concat("子单号：").concat(salesOrderItem.getCustSalesOrderItemNo())
                            .concat(salesOrderItem.getCustSpuId());
                    salesOrderItem.setGenAccFailedReason(msg);
                }else{
                    salesOrderItem.setErrorFlag("Y");
                    salesOrderItem.setErrorCode("301");
                    String msg = "301-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo())
                            .concat(salesOrderItem.getCustSpuId()).concat("有折扣编码：")
                            .concat(salesOrderItem.getDiscountActivityCode()).concat("无法找到活动价格。");
                    salesOrderItem.setGenAccFailedReason(msg);
                }
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                return  "费率没有查到";
            }else{
                disctFlag = "Y";
            }
        }else{
            //先查有没有活动
            PromotionDiscountPriceSearchParam promotionDiscountPriceSearchParam
                    = new PromotionDiscountPriceSearchParam();
            promotionDiscountPriceSearchParam.setMallCustNo(salesOrderItem.getCustomerNo());
            promotionDiscountPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());
            promotionDiscountPriceSearchParam.setEffectUntilDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            promotionDiscountPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));


            if(!StringUtils.isNull(salesOrderItem.getMaterialMapId())){
                promotionDiscountPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                //   promotionDiscountPriceSearchParam.setActType("!");
                apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);
            }
            if(apamt==0.0) {
                promotionDiscountPriceSearchParam.setMaterialMapId(null);
                materialBuyPriceSearchParam.setMaterialMapId(null);
                promotionDiscountPriceSearchParam.setCsaSkuCode("通用");
                promotionDiscountPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                promotionDiscountPriceSearchParam.setActType("!=");
                apamt= this.getBuyTotalDisctAmount(salesOrderItem, promotionDiscountPriceSearchParam,materialBuyPriceSearchParam);

            }
            if(apamt==0.0) {
                // 查正常活动
                SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
               /* if(!StringUtils.isNull(salesOrderItem.getErrorCode())&&salesOrderItem.getErrorCode().equals("1001")){
                    salesOrderItem.setErrorFlag("Y");
                    String msg = salesOrderItem.getErrorCode().concat("子订单号：").concat(salesOrderItem.getCustSalesOrderItemNo())
                            .concat(salesOrderItem.getCustSpuId());
                    salesOrderItem.setGenAccFailedReason(msg);
                    BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                    this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                    return  "活动费率重复";
                }*/

                materialBuyPriceSearchParam.setMallCustNo(salesOrderItem.getCustomerNo());
                materialBuyPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));


                materialBuyPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());
                if(!StringUtils.isNull(salesOrderItem.getMaterialMapId())){
                    materialBuyPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                    apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                    if(apamt==0.0) {
                        materialBuyPriceSearchParam.setMaterialMapId(null);
                        materialBuyPriceSearchParam.setMaterialMapId(null);
                        materialBuyPriceSearchParam.setCsaSkuCode("通用");
                        materialBuyPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                        apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                    }

                }else  if(!StringUtils.isNull(salesOrderItem.getGoodGroupId())){
                    materialBuyPriceSearchParam.setGoodGroupId(salesOrderItem.getGoodGroupId());
                    apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                }

            }else{
                disctFlag = "Y";
            }

        }

        if (!StringUtils.isNull(salesOrderItem.getStoreDiscountCode())
                &&salesOrderItem.getStoreDiscountCode()!="") {//搞活动
            Double storeDiscount = 0.0;
            PromotionDiscountPriceSearchParam promotionDiscountPriceSearchParam
                    = new PromotionDiscountPriceSearchParam();
            promotionDiscountPriceSearchParam.setMallCustNo(salesOrderItem.getCustomerNo());
            promotionDiscountPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());
            promotionDiscountPriceSearchParam.setEffectUntilDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            promotionDiscountPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));
            String storedisctflag = "N";
            double storeCuponDisct = 0.0;
            if(salesOrderItem.getStoreDiscountAmt()!=null){
                storeDiscount = salesOrderItem.getStoreDiscountAmt();
                storeCuponDisct = NumberUtils.add(storeCuponDisct,storeDiscount);
                if(!StringUtils.isNull(salesOrderItem.getActivityName())){
                    if(salesOrderItem.getActivityName().contains("直播")||salesOrderItem.getActivityName().contains("秒杀"))
                        apamt = NumberUtils.sub(apamt,storeCuponDisct);
                }


                if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                    Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeCuponDisct);
                    salesOrderItem.setPayMoney(ar);
                }
                storedisctflag = "Y";
            }
            if(salesOrderItem.getStoreDiscountAmtPoint()!=null){
                storeDiscount = NumberUtils.mul(salesOrderItem.getStoreDiscountAmtPoint(),0.05);
                storeCuponDisct = NumberUtils.add(storeCuponDisct,storeDiscount);
                if(!StringUtils.isNull(salesOrderItem.getActivityName())){
                    if(salesOrderItem.getActivityName().contains("直播")||salesOrderItem.getActivityName().contains("秒杀"))
                        apamt = NumberUtils.sub(apamt,storeCuponDisct);
                }

                if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                    Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeCuponDisct);
                    salesOrderItem.setPayMoney(ar);
                }

                storedisctflag = "Y";
            }


       /*     if(storedisctflag.equals("N")){
                if(!StringUtils.isNull(salesOrderItem.getMaterialMapId())) {
                    promotionDiscountPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                    materialBuyPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                    storeDiscount = this.getBuyTotalCuponAmount(salesOrderItem, promotionDiscountPriceSearchParam, materialBuyPriceSearchParam);
                    salesOrderItem.setStoreDiscountAmt(storeDiscount);
                    apamt = NumberUtils.sub(apamt, storeDiscount);
                    if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                        Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeDiscount);
                        salesOrderItem.setPayMoney(ar);
                    }

                    if(apamt==0.0) {
                        promotionDiscountPriceSearchParam.setMaterialMapId(null);
                        materialBuyPriceSearchParam.setMaterialMapId(null);
                        promotionDiscountPriceSearchParam.setCsaSkuCode("通用");
                        promotionDiscountPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                        storeDiscount = this.getBuyTotalCuponAmount(salesOrderItem, promotionDiscountPriceSearchParam, materialBuyPriceSearchParam);
                        salesOrderItem.setStoreDiscountAmt(storeDiscount);
                        apamt = NumberUtils.sub(apamt, storeDiscount);
                        if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                            Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeDiscount);
                            salesOrderItem.setPayMoney(ar);
                        }
                    }
                }
            }*/

        }



        // generateApList
        if(salesOrderItem.getBuyPrice()==null||salesOrderItem.getBuyPrice().doubleValue()==0.0) {
            salesOrderItem.setBuyPrice(apamt);
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();


            if(apamt==0.0){
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setErrorCode("203");
                String msg = "203-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                        .concat(salesOrderItem.getCustSpuId()).concat("无法找到常规价格。");
                salesOrderItem.setGenAccFailedReason(msg);

                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
                this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
                return  "费率没有查到";

            }
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
            salesOrderItem.setGenAccFailedReason("");
            BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
            this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
        }else if(apamt==0.0){
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();

            salesOrderItem.setErrorFlag("Y");
            salesOrderItem.setErrorCode("203");
            String msg = "203-子订单号：".concat(salesOrderItem.getCustSalesOrderItemNo()).concat(",")
                    .concat(salesOrderItem.getCustSpuId()).concat("无法找到常规价格。");
            salesOrderItem.setGenAccFailedReason(msg);
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
            BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
            this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
            return  "费率没有查到";
        }else{
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();
            salesOrderItem.setGenAccFailedReason("");
            salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
            salesOrderItem.setGenAccFailedReason("");
            BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
            this.salesOrderItemService.updateFromAsnc(salesOrderItem.getId(), salesOrderItemSaveParam,userVo);
        }

        String apgenerateResult = this.generateApList(apamt,salesOrderItem,userVo);
        return rt;


    }
    /**
     * 生成财务应付数据
     * @param apamt
     * @param salesOrderItem
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String generateApList(Double apamt,SalesOrderItemVo salesOrderItem,UserVo userVo){
        AccountingAp accountingAp = new AccountingAp();
        if(apamt==null){
            apamt = 0.0;
        }
        if(apamt!=null&&apamt.doubleValue()>0.0){
            if(salesOrderItem.getQty()!=null&&salesOrderItem.getQty().longValue()>0){
                Double rate = NumberUtils.div(apamt.doubleValue(),salesOrderItem.getQty());
                accountingAp.setAmount(apamt);
                accountingAp.setRate(new BigDecimal(rate));
            }else{
                Double rate = NumberUtils.div(apamt.doubleValue(),1);
                accountingAp.setAmount(apamt);
                accountingAp.setRate(new BigDecimal(rate));
            }

        }

        if(salesOrderItem.getQty()!=null){
            accountingAp.setOriginalSellQty(salesOrderItem.getQty().intValue());
        }
        if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
            accountingAp.setContractAmount(Double.valueOf(salesOrderItem.getCustRelSalesPrice())); //营销委结算价
        }
        if(salesOrderItem.getPayMoney()!=null) {
            accountingAp.setAmtAr(Double.valueOf(salesOrderItem.getPayMoney()));
        }else{
            accountingAp.setAmtAr(Double.valueOf(salesOrderItem.getCustRelSalesPrice()));
        }
        if(salesOrderItem.getReturnAmt()!=null){
            Double amt = NumberUtils.add(accountingAp.getAmtAr(),salesOrderItem.getReturnAmt());
            accountingAp.setSalesOriginAmount(amt);
        }else{
            accountingAp.setSalesOriginAmount(accountingAp.getAmtAr());
        }
        if(salesOrderItem.getAmtGenAr()!=null){
            accountingAp.setAmtGenAr(salesOrderItem.getAmtGenAr());
            Double sellPriceTot = NumberUtils.mul(salesOrderItem.getAmtGenAr(),salesOrderItem.getQty());
            accountingAp.setAmtCur(new BigDecimal(sellPriceTot));
        }
        accountingAp.setCustRelSalesUnitPrice(salesOrderItem.getCustRelSalesUnitPrice());
        accountingAp.setBasicNo(salesOrderItem.getSalesOrderNo());
        // 对方子订单号
        accountingAp.setSourceItemId(salesOrderItem.getCustSalesOrderItemNo());
        accountingAp.setCustSkuId(salesOrderItem.getCustSkuId());
        accountingAp.setCustSpuId(salesOrderItem.getCustSpuId());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        if(!StringUtils.isNull(salesOrderItem.getCustSkuId())){
            accountingAp.setCargoObjectNo(salesOrderItem.getCustSkuId());
            List<SkuVo> skus =  skuMapper.findByCustSkuId(salesOrderItem.getCustSkuId(),salesOrderItem.getCustomerNo());
            if(skus!=null&&skus.size()>0){
                SkuVo sku = (SkuVo)skus.get(0);
                accountingAp.setCargoObjectName(sku.getSkuName());
            }else{
                accountingAp.setCargoObjectName(salesOrderItem.getSkuName());
            }
        }else{
            accountingAp.setCargoObjectNo(salesOrderItem.getCustSpuId());
            List<Spu> spus = spuMapper.findByCustSpuNo(salesOrderItem.getCustSpuId(),salesOrderItem.getCustomerNo());
            if(spus!=null&&spus.size()>0){
                Spu spu = (Spu)spus.get(0);
                accountingAp.setCargoObjectName(spu.getSpuName());
            }else{

                accountingAp.setCargoObjectName(salesOrderItem.getSkuName());
            }
        }


        accountingAp.setCustSaleUnitPrice(salesOrderItem.getCustSaleUnitPrice());
        accountingAp.setCustSaleUnitMile(salesOrderItem.getCustSaleUnitMile());
        if(!StringUtils.isNull(salesOrderItem.getCustCashPaymentAmt())){
            if(StringUtils.isDouble(salesOrderItem.getCustCashPaymentAmt())){
                accountingAp.setCustCashPaymentAmt(Double.valueOf(salesOrderItem.getCustCashPaymentAmt()));
            }else{
                String amt = salesOrderItem.getCustCashPaymentAmt().substring(1);
                accountingAp.setCustCashPaymentAmt(Double.valueOf(amt));

            }
        }
        if(!StringUtils.isNull(salesOrderItem.getCustMilePaymentAmt())){
            if(StringUtils.isDouble(salesOrderItem.getCustMilePaymentAmt())){
                accountingAp.setCustMilePaymentAmt(Double.valueOf(salesOrderItem.getCustMilePaymentAmt()));
            }else{
                String amt = salesOrderItem.getCustMilePaymentAmt().substring(1);
                accountingAp.setCustMilePaymentAmt(Double.valueOf(amt));

            }
        }

        accountingAp.setDiscountActivityCode(salesOrderItem.getDiscountActivityCode());
        accountingAp.setStoreDiscountActId(salesOrderItem.getStoreDiscountActId());
        accountingAp.setStoreDiscountCode(salesOrderItem.getStoreDiscountCode());
        accountingAp.setStoreDiscountAmt(salesOrderItem.getStoreDiscountAmt());
        accountingAp.setStoreDiscountAmtPoint(salesOrderItem.getStoreDiscountAmtPoint());
        accountingAp.setMallName(salesOrderItem.getCustomerName());
        accountingAp.setStoreName(salesOrderItem.getStoreName());
        accountingAp.setShipperName(salesOrderItem.getSupplierName());
        accountingAp.setOriginalCustName(salesOrderItem.getSupplierName());
        accountingAp.setStoreCuponCash(salesOrderItem.getStoreDiscountAmt());
        accountingAp.setStoreCuponMile(salesOrderItem.getStoreDiscountAmtPoint());
        if(!StringUtils.isNull(salesOrderItem.getSupplierNo())){
            accountingAp.setPayCust(salesOrderItem.getSupplierNo()); // 付出去的 收款人
            accountingAp.setShipperName(salesOrderItem.getSupplierName());
            accountingAp.setOriginalCustName(salesOrderItem.getSupplierName());
        }else{
            Store store = this.storeMapper.findStoreByCode(salesOrderItem.getStoreId());
            if(store!=null){
                accountingAp.setPayCust(store.getSupplierId()); // 付出去的 收款人
                accountingAp.setShipperName(store.getSupplierName());
                accountingAp.setOriginalCustName(store.getSupplierName());
            }
        }


        accountingAp.setBillToCust(salesOrderItem.getMallBuyerNo()); // 付款人
        accountingAp.setPaiedFee(new BigDecimal(0.0));
        accountingAp.setConsigneeName(salesOrderItem.getConsigneeName());

        accountingAp.setContractRate(apamt);

        accountingAp.setRemainedAmount(apamt);
        accountingAp.setFrtCd("10001");
        accountingAp.setFrtNm("purchase");
        accountingAp.setInputType("A");
        accountingAp.setMallId(salesOrderItem.getCustomerNo());
        accountingAp.setStoreId(salesOrderItem.getStoreId());

        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(salesOrderItem.getOrderTime());
        accountingAp.setOrderSeqNo(salesOrderItem.getSalesOrderId());
        accountingAp.setOriginalCustName(salesOrderItem.getMallBuyerNo());
        if(!StringUtils.isNull(accountingAp.getJobDate())){
            String [] today =accountingAp.getJobDate().split(" ");
            accountingAp.setMonthYearDate(today[0]);

        }

        accountingAp.setSite(userVo.getOrgId());
        accountingAp.setReturnAmt(salesOrderItem.getReturnAmt());
        accountingAp.setReturnQty(salesOrderItem.getReturnQty());
        accountingAp.setReturnOrderItemNo(salesOrderItem.getReturnOrderItemNo());

        SpuVo spu =spuMapper.findById(salesOrderItem.getSpuId());
        if(spu!=null){
            accountingAp.setBrandName(spu.getBrandName());
        }
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQty()));
        String[] jobdt = accountingAp.getJobDate().split("-");
        accountingAp.setMonthYear(jobdt[0].concat("-").concat(jobdt[1]));

        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        if(apamt==null){
            accountingAp.setAmount(0.0);
        }
        this.mapper.insert(accountingAp);

        return "success";
    }
    /**
     * 供应商对账减
     *
     * @param  accountingApSaveParam
     * @return
     */
    public String handleAdjustSub(AccountingApSaveParam accountingApSaveParam){
        return "success";
    }

    /**
     * 供应商对账减
     *
     * @param  accountingApSaveParam
     * @return
     */
    public String handleAdjustAdd(AccountingApSaveParam accountingApSaveParam){
        return "success";
    }
    /**
     * 品牌排行列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccountingApVo> brandRateView(AccountingApSearchParam params, Integer current, Integer pageSize){
        return this.mapper.brandRateView(new Page<>(current, pageSize), params);
    }

    /**
     * 供应商排行列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccountingApVo> supplierRateView(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.supplierRateView(new Page<>(current, pageSize), params);
    }


    /**
     * xiaoshoufenxi-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccountingApViewVo> skuReport(AccountingApSearchParam params, Integer current, Integer pageSize) {
        if(StringUtils.isNull(params.getCustSkuId())){
            return this.mapper.spuReport(new Page<>(current, pageSize), params);
        }else{
            return this.mapper.skuReport(new Page<>(current, pageSize), params);
        }
    }
   /* @Override
    public IPage<AccountingApVo> skuReport(AccountingApSearchParam params, Integer current, Integer pageSize) {
        if(StringUtils.isNull(params.getJobDateFr())&&StringUtils.isNull(params.getJobDateTo())){
            Date today = new Date();
            Date sixtyBefore = DateUtils.getDateBefore(today,30);
            String td = DateUtils.formatDate(sixtyBefore);
            params.setJobDateFr(td);
            if(StringUtils.isNull(params.getStoreId())){
                return this.mapper.skuReportFrAllStore(new Page<>(current, pageSize), params);
            }else{
                if(StringUtils.isNull(params.getCustSpuId())){
                    return this.mapper.skuReportFrAllSpu(new Page<>(current, pageSize), params);
                }else{
                    return this.mapper.skuReportFr(new Page<>(current, pageSize), params);
                }
            }
        }else  if(StringUtils.isNull(params.getJobDateFr())){
            if(StringUtils.isNull(params.getStoreId())){
                return this.mapper.skuReportToAllStore(new Page<>(current, pageSize), params);
            }else{
                if(StringUtils.isNull(params.getCustSpuId())){
                    return this.mapper.skuReportToAllSpu(new Page<>(current, pageSize), params);
                }else{
                    return this.mapper.skuReportTo(new Page<>(current, pageSize), params);
                }
            }

        }else  if(StringUtils.isNull(params.getJobDateTo())){
            if(StringUtils.isNull(params.getStoreId())){
                return this.mapper.skuReportFrAllStore(new Page<>(current, pageSize), params);
            }else{
                if(StringUtils.isNull(params.getCustSpuId())){
                    return this.mapper.skuReportFrAllSpu(new Page<>(current, pageSize), params);
                }else{
                    return this.mapper.skuReportFr(new Page<>(current, pageSize), params);
                }
            }
        }else{
            if(StringUtils.isNull(params.getStoreId())){
                return this.mapper.skuReportStoreAll(new Page<>(current, pageSize), params);
            }else{
                if(StringUtils.isNull(params.getCustSpuId())){
                    return this.mapper.skuReportStoreAllSpu(new Page<>(current, pageSize), params);
                }else{
                    return this.mapper.skuReportStore(new Page<>(current, pageSize), params);
                }
            }
        }

    }*/


    /**
     * 处理退单
     * @param idList
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String processReturn(List<String> idList){
        String rt =  "success";
        if (ListUtils.isNotEmpty(idList)) {
            for(int i=0;i <idList.size(); i++){
                String rtOrderId = (String)idList.get(i);
                ReturnOrderItem item = this.returnOrderItemMapper.selectById(rtOrderId);
                if(!StringUtils.isNull(item.getErrorFlag())){
                    if(item.getErrorFlag().equals("Y")){
                        // continue;
                    }
                }
                String custOrderItemNo = item.getCustSalesOrderItemNo();
                if(!StringUtils.isNull(custOrderItemNo)) {
                    if(custOrderItemNo.contains("SC")){
                        custOrderItemNo = custOrderItemNo.substring(2);
                    }
                }
                //  SalesOrderItem sov = this.salesOrderItemmapper.findByEntityCustSalesOrderItemNo(custOrderItemNo);
                SalesOrderItem sov = null;
                if(!StringUtils.isNull(item.getCustSkuId())){
                    List<SalesOrderItem>  sovs=  this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSkuCode(custOrderItemNo,item.getCustSkuId());
                    if(sovs!=null&&sovs.size()>0){
                        sov= sovs.get(0);
                    }
                }else if(!StringUtils.isNull(item.getCustSkuId())){
                    List<SalesOrderItem>  sovs=  this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSpuCode(custOrderItemNo,item.getCustSpuId());
                    if(sovs!=null&&sovs.size()>0){
                        sov= sovs.get(0);
                    }
                }else{
                    item.setImportErrorMesg("退单没有提供商品SKU编号");
                    if(!StringUtils.isNull(item.getErrorCode())){
                        item.setErrorCode(item.getErrorCode().concat(";").concat("129"));
                    }else{
                        item.setErrorCode("129");
                    }
                    item.setErrorFlag("Y");
                    UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                    this.genOperationLog(item,user);
                    item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                    this.returnOrderItemMapper.updateById(item);

                    continue;
                }
                if(sov==null){
                    UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                    item.setImportErrorMesg("原始订单不存在");
                    if(!StringUtils.isNull(item.getErrorCode())){
                        item.setErrorCode(item.getErrorCode().concat(";").concat("123"));
                    }else{
                        item.setErrorCode("123");
                    }
                    item.setErrorFlag("Y");

                    this.genOperationLog(item,user);
                    item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                    this.returnOrderItemMapper.updateById(item);

                    continue;
                }
                Double returnAmt = 0.0;
                if(item.getBuyPrice()!=null&&item.getQty()!=null){
                    returnAmt = NumberUtils.mul(item.getBuyPrice(),item.getQty());
                }else if(item.getMoney()!=null){
                    returnAmt = item.getMoney();
                }
                if(item.getCouponDiscount()!=null){
                    returnAmt =NumberUtils.sub(returnAmt,item.getCouponDiscount());
                }
                if(item.getMileageCouponDiscount()!=null){
                    Double mileamt =  NumberUtils.mul(item.getMileageCouponDiscount(),0.05);
                    returnAmt = NumberUtils.sub(returnAmt,mileamt);
                }

                if(!StringUtils.isNull(sov.getIsReturn())){
                    if(sov.getIsReturn().equals("Y")){
                        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                        item.setImportErrorMesg("退单已经处理，不可重复处理");
                        this.genOperationLog(item,user);
                        if(!StringUtils.isNull(item.getErrorCode())){
                            item.setErrorCode(item.getErrorCode().concat(";").concat("124"));
                        }else{
                            item.setErrorCode("124");
                        }
                        item.setErrorFlag("Y");
                        item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                        this.returnOrderItemMapper.updateById(item);

                        continue;
                    }
                }

                if(sov.getStatus().equals("acc_gen")){
                    Long nowqty =sov.getQty();
                    if(item.getQty()!=null){
                        nowqty = sov.getQty()-item.getQty();
                        sov.setReturnQty(item.getQty().intValue());

                    }else{
                        sov.setReturnQty(sov.getQty().intValue());
                        nowqty = new Long(0);

                    }
                    sov.setQty(nowqty);

                    List<AccountingAp> accountAps = this.mapper.findByOrderItemNo(sov.getId());
                    if(accountAps!=null&&accountAps.size()>0){
                        AccountingAp accountAp = accountAps.get(0);
                        if(accountAp.getStatus().equals("settled")){
                            sov.setIsReturn("N");
                            item.setStatus(ReturnOrderStatusEnum.SETTLED.getValue());
                            item.setImportErrorMesg("退单已经汇总下账，请取消下账");
                            if(!StringUtils.isNull(item.getErrorCode())){
                                item.setErrorCode(item.getErrorCode().concat(";").concat("125"));
                            }else{
                                item.setErrorCode("125");
                            }
                            item.setErrorFlag("Y");
                            this.returnOrderItemMapper.updateById(item);
                            continue;
                        }
                        if(accountAp.getAmtAr()!=null){
                            // Double arRate = NumberUtils.div(accountAp.getAmtAr(),accountAp.getWtCnt().doubleValue());
                            Double nowar = NumberUtils.sub(accountAp.getAmtAr(),returnAmt);
                            accountAp.setAmtAr(nowar);
                        }
                        accountAp.setStoreCuponCash(item.getCouponDiscount());
                        accountAp.setStoreCuponMile(item.getMileageCouponDiscount());


                        if(accountAp.getRate()!=null) {
                            Double returnTotnowAmt = NumberUtils.mul(nowqty, accountAp.getRate().doubleValue());
                            accountAp.setAmount(returnTotnowAmt);
                        }
                        accountAp.setWtCnt(BigDecimal.valueOf(nowqty));
                        accountAp.setReturnAmt(returnAmt);
                        if(!StringUtils.isNull(item.getLastUpdDt())){
                            String retDate = this.removeSpecialChar(item.getLastUpdDt());
                            accountAp.setReturnTime(DateUtils.parseDate(retDate));
                            retDate =retDate.substring(0,7);
                            accountAp.setReturnMonthYearDate(retDate);
                        }
                        if(accountAp.getRate()!=null){
                            Double buyrt = NumberUtils.mul(accountAp.getRate().doubleValue(),item.getQty().doubleValue());
                            accountAp.setBuyReturnAmt(buyrt);
                        }

                        accountAp.setReturnQty(item.getQty().intValue());
                        accountAp.setReturnOrderItemNo(item.getCustReturnOrderItemNo());
                        this.mapper.updateById(accountAp);
                    }

                    sov.setIsReturn("Y");
                    sov.setReturnAmt(returnAmt);
                    sov.setReturnQty(item.getQty().intValue());
                    sov.setReturnOrderItemNo(item.getCustSalesOrderItemNo());
                    this.salesOrderItemmapper.updateById(sov);


                    item.setStatus(ReturnOrderStatusEnum.PROCESSED.getValue());
                    this.returnOrderItemMapper.updateById(item);
                }else if(sov.getStatus().equals("newRece")||sov.getStatus().equals("acc_failed")){
                  /*  Long nowqty =sov.getQty();
                    nowqty = sov.getQty()-item.getQty();
                    sov.setQty(nowqty);
                    sov.setReturnAmt(item.getMoney());
                    sov.setReturnQty(item.getQty().intValue());
                    sov.setReturnOrderItemNo(item.getCustSalesOrderItemNo());
                    sov.setIsReturn("Y");
                    this.salesOrderItemmapper.updateById(sov);
                    item.setStatus(ReturnOrderStatusEnum.PROCESSED.getValue());

                    this.returnOrderItemMapper.updateById(item);*/
                    UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                    item.setImportErrorMesg("原始订单还未结算，请等结算之后处理");
                    this.genOperationLog(item,user);
                    this.returnOrderItemMapper.updateById(item);
                    continue;
                }else if(sov.getStatus().equals("rtApplied")){

                }else{

                }
            }


        } else {
            return "noData";
        }
        return rt;
    }

    /**
     * 处理退单
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String reprocessReturn(){
        String rt =  "success";
        ReturnOrderItemSearchParam returnOrderItemSearchParam
                = new ReturnOrderItemSearchParam();
        returnOrderItemSearchParam.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
        List<ReturnOrderItem> rtlists = returnOrderItemMapper.findEntityAll(returnOrderItemSearchParam);

        for(int i=0;i <rtlists.size(); i++){
            ReturnOrderItem item = (ReturnOrderItem)rtlists.get(i);

            String custOrderItemNo = item.getCustSalesOrderItemNo();
            if(!StringUtils.isNull(custOrderItemNo)) {
                if(custOrderItemNo.contains("SC")){
                    custOrderItemNo = custOrderItemNo.substring(2);
                }
            }
            SalesOrderItem sov = null;
            if(!StringUtils.isNull(item.getCustSkuId())){
                List<SalesOrderItem>  sovs=  this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSkuCode(custOrderItemNo,item.getCustSkuId());
                if(sovs!=null&&sovs.size()>0){
                    sov= sovs.get(0);
                }
            }else if(!StringUtils.isNull(item.getCustSpuId())){
                List<SalesOrderItem>  sovs=  this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSpuCode(custOrderItemNo,item.getCustSpuId());
                if(sovs!=null&&sovs.size()>0){
                    sov= sovs.get(0);
                }
            }else{
                item.setImportErrorMesg("退单没有提供商品SKU编号");
                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                if(!StringUtils.isNull(item.getErrorCode())){
                    item.setErrorCode(item.getErrorCode().concat(";").concat("129"));
                }else{
                    item.setErrorCode("129");
                }
                item.setErrorFlag("Y");
                this.genOperationLog(item,user);
                item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                this.returnOrderItemMapper.updateById(item);
                continue;
            }
            if(sov==null){
                item.setImportErrorMesg("原始订单不存在");
                if(!StringUtils.isNull(item.getErrorCode())){
                    item.setErrorCode(item.getErrorCode().concat(";").concat("123"));
                }else{
                    item.setErrorCode("123");
                }
                item.setErrorFlag("Y");
                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                this.genOperationLog(item,user);
                item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                this.returnOrderItemMapper.updateById(item);
                continue;
            }
            Double returnAmt = 0.0;
            if(item.getBuyPrice()!=null&&item.getQty()!=null){
                returnAmt = NumberUtils.mul(item.getBuyPrice(),item.getQty());
            }else if(item.getMoney()!=null){
                returnAmt = item.getMoney();
            }
            if(item.getCouponDiscount()!=null){
                returnAmt =NumberUtils.sub(returnAmt,item.getCouponDiscount());
            }
            if(item.getMileageCouponDiscount()!=null){
                Double mileamt =  NumberUtils.mul(item.getMileageCouponDiscount(),0.05);
                returnAmt = NumberUtils.sub(returnAmt,mileamt);
            }

            if(!StringUtils.isNull(sov.getIsReturn())){
                if(sov.getIsReturn().equals("Y")){
                    UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                    item.setImportErrorMesg("退单已经处理，不可重复处理");
                    this.genOperationLog(item,user);
                    if(!StringUtils.isNull(item.getErrorCode())){
                        item.setErrorCode(item.getErrorCode().concat(";").concat("124"));
                    }else{
                        item.setErrorCode("124");
                    }
                    item.setErrorFlag("Y");
                    item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                    this.returnOrderItemMapper.updateById(item);

                    continue;
                }
            }

            if(sov.getStatus().equals("acc_gen")){
                Long nowqty =sov.getQty();
                if(item.getQty()!=null){
                    nowqty = sov.getQty()-item.getQty();
                    sov.setReturnQty(item.getQty().intValue());

                }else{
                    sov.setReturnQty(sov.getQty().intValue());
                    nowqty = new Long(0);

                }
                sov.setQty(nowqty);

                List<AccountingAp> accountAps = this.mapper.findByOrderItemNo(sov.getId());
                if(accountAps!=null&&accountAps.size()>0){
                    AccountingAp accountAp = accountAps.get(0);
                    if(accountAp.getStatus().equals("settled")){
                        sov.setIsReturn("N");
                        item.setStatus(ReturnOrderStatusEnum.SETTLED.getValue());
                        item.setImportErrorMesg("退单已经汇总下账，请取消下账");
                        if(!StringUtils.isNull(item.getErrorCode())){
                            item.setErrorCode(item.getErrorCode().concat(";").concat("125"));
                        }else{
                            item.setErrorCode("125");
                        }
                        item.setErrorFlag("Y");
                        this.returnOrderItemMapper.updateById(item);
                        continue;
                    }
                    if(accountAp.getAmtAr()!=null){
                        // Double arRate = NumberUtils.div(accountAp.getAmtAr(),accountAp.getWtCnt().doubleValue());
                        Double nowar = NumberUtils.sub(accountAp.getAmtAr(),returnAmt);
                        accountAp.setAmtAr(nowar);
                    }
                    accountAp.setStoreCuponCash(item.getCouponDiscount());
                    accountAp.setStoreCuponMile(item.getMileageCouponDiscount());


                    if(accountAp.getRate()!=null) {
                        Double returnTotnowAmt = NumberUtils.mul(nowqty, accountAp.getRate().doubleValue());
                        accountAp.setAmount(returnTotnowAmt);
                    }
                    accountAp.setWtCnt(BigDecimal.valueOf(nowqty));
                    // String retDate = DateUtils.formatDate(new Date());
                    //   retDate =retDate.substring(0,7);
                    //   accountAp.setReturnMonthYearDate(retDate);

                    if(!StringUtils.isNull(item.getLastUpdDt())){
                        String retDate=this.removeSpecialChar(item.getLastUpdDt());
                        accountAp.setReturnTime(DateUtils.parseDate(retDate));
                        retDate =retDate.substring(0,7);
                        accountAp.setReturnMonthYearDate(retDate);
                    }
                    if(accountAp.getRate()!=null){
                        Double buyrt = NumberUtils.mul(accountAp.getRate().doubleValue(),item.getQty().doubleValue());
                        accountAp.setBuyReturnAmt(buyrt);
                    }
                    accountAp.setReturnAmt(returnAmt);
                    accountAp.setReturnQty(item.getQty().intValue());
                    accountAp.setReturnOrderItemNo(item.getCustReturnOrderItemNo());
                    this.mapper.updateById(accountAp);
                }

                sov.setIsReturn("Y");
                sov.setReturnAmt(returnAmt);
                sov.setReturnQty(item.getQty().intValue());
                sov.setReturnOrderItemNo(item.getCustSalesOrderItemNo());
                this.salesOrderItemmapper.updateById(sov);


                item.setStatus(ReturnOrderStatusEnum.PROCESSED.getValue());
                this.returnOrderItemMapper.updateById(item);
            }else if(sov.getStatus().equals("newRece")||sov.getStatus().equals("acc_failed")){

                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                item.setImportErrorMesg("原始订单还未结算，请等结算之后处理");
                this.genOperationLog(item,user);
                this.returnOrderItemMapper.updateById(item);
                continue;
            }else if(sov.getStatus().equals("rtApplied")){

            }else{

            }
        }
        return rt;
    }
    /**
     * 处理退单
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String processReturnAll(){
        String rt =  "success";
        ReturnOrderItemSearchParam returnOrderItemSearchParam
                = new ReturnOrderItemSearchParam();
        returnOrderItemSearchParam.setStatus(ReturnOrderStatusEnum.NEWREC.getValue());
        List<ReturnOrderItem> rtlists = returnOrderItemMapper.findEntityAll(returnOrderItemSearchParam);

        for(int i=0;i <rtlists.size(); i++){
            ReturnOrderItem item = (ReturnOrderItem)rtlists.get(i);
            if(!StringUtils.isNull(item.getErrorFlag())){
                if(item.getErrorFlag().equals("Y")){
                    item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                    this.returnOrderItemMapper.updateById(item);
                    continue;
                }
            }
            String custOrderItemNo = item.getCustSalesOrderItemNo();
            if(!StringUtils.isNull(custOrderItemNo)) {
                if(custOrderItemNo.contains("SC")){
                    custOrderItemNo = custOrderItemNo.substring(2);
                }
            }
            SalesOrderItem sov = null;
            if(!StringUtils.isNull(item.getCustSkuId())){
                List<SalesOrderItem>  sovs=  this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSkuCode(custOrderItemNo,item.getCustSkuId());
                if(sovs!=null&&sovs.size()>0){
                    sov= sovs.get(0);
                }
            }else if(!StringUtils.isNull(item.getCustSpuId())){
                List<SalesOrderItem>  sovs=  this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSpuCode(custOrderItemNo,item.getCustSpuId());
                if(sovs!=null&&sovs.size()>0){
                    sov= sovs.get(0);
                }
            }else{
                item.setImportErrorMesg("退单没有提供商品SKU编号");
                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                if(!StringUtils.isNull(item.getErrorCode())){
                    item.setErrorCode(item.getErrorCode().concat(";").concat("129"));
                }else{
                    item.setErrorCode("129");
                }
                item.setErrorFlag("Y");
                this.genOperationLog(item,user);
                item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                this.returnOrderItemMapper.updateById(item);
                continue;
            }
            if(sov==null){
                item.setImportErrorMesg("原始订单不存在");
                if(!StringUtils.isNull(item.getErrorCode())){
                    item.setErrorCode(item.getErrorCode().concat(";").concat("123"));
                }else{
                    item.setErrorCode("123");
                }
                item.setErrorFlag("Y");
                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                this.genOperationLog(item,user);
                item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                this.returnOrderItemMapper.updateById(item);
                continue;
            }
            Double returnAmt = 0.0;
            if(item.getBuyPrice()!=null&&item.getQty()!=null){
                returnAmt = NumberUtils.mul(item.getBuyPrice(),item.getQty());
            }else if(item.getMoney()!=null){
                returnAmt = item.getMoney();
            }
            if(item.getCouponDiscount()!=null){
                returnAmt =NumberUtils.sub(returnAmt,item.getCouponDiscount());
            }
            if(item.getMileageCouponDiscount()!=null){
                Double mileamt =  NumberUtils.mul(item.getMileageCouponDiscount(),0.05);
                returnAmt = NumberUtils.sub(returnAmt,mileamt);
            }

            if(!StringUtils.isNull(sov.getIsReturn())){
                if(sov.getIsReturn().equals("Y")){
                    UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                    item.setImportErrorMesg("退单已经处理，不可重复处理");
                    this.genOperationLog(item,user);
                    if(!StringUtils.isNull(item.getErrorCode())){
                        item.setErrorCode(item.getErrorCode().concat(";").concat("124"));
                    }else{
                        item.setErrorCode("124");
                    }
                    item.setErrorFlag("Y");
                    item.setStatus(ReturnOrderStatusEnum.ERROR.getValue());
                    this.returnOrderItemMapper.updateById(item);

                    continue;
                }
            }

            if(sov.getStatus().equals("acc_gen")){
                Long nowqty =sov.getQty();
                if(item.getQty()!=null){
                    nowqty = sov.getQty()-item.getQty();
                    sov.setReturnQty(item.getQty().intValue());

                }else{
                    sov.setReturnQty(sov.getQty().intValue());
                    nowqty = new Long(0);

                }
                sov.setQty(nowqty);

                List<AccountingAp> accountAps = this.mapper.findByOrderItemNo(sov.getId());
                if(accountAps!=null&&accountAps.size()>0){
                    AccountingAp accountAp = accountAps.get(0);
                    if(accountAp.getStatus().equals("settled")){
                        sov.setIsReturn("N");
                        item.setStatus(ReturnOrderStatusEnum.SETTLED.getValue());
                        item.setImportErrorMesg("退单已经汇总下账，请取消下账");
                        if(!StringUtils.isNull(item.getErrorCode())){
                            item.setErrorCode(item.getErrorCode().concat(";").concat("125"));
                        }else{
                            item.setErrorCode("125");
                        }
                        item.setErrorFlag("Y");
                        this.returnOrderItemMapper.updateById(item);
                        continue;
                    }
                    if(accountAp.getAmtAr()!=null){
                        // Double arRate = NumberUtils.div(accountAp.getAmtAr(),accountAp.getWtCnt().doubleValue());
                        Double nowar = NumberUtils.sub(accountAp.getAmtAr(),returnAmt);
                        accountAp.setAmtAr(nowar);
                    }
                    accountAp.setStoreCuponCash(item.getCouponDiscount());
                    accountAp.setStoreCuponMile(item.getMileageCouponDiscount());


                    if(accountAp.getRate()!=null) {
                        Double returnTotnowAmt = NumberUtils.mul(nowqty, accountAp.getRate().doubleValue());
                        accountAp.setAmount(returnTotnowAmt);
                    }
                    accountAp.setWtCnt(BigDecimal.valueOf(nowqty));
                    if(accountAp.getRate()!=null){
                        Double buyrt = NumberUtils.mul(accountAp.getRate().doubleValue(),item.getQty().doubleValue());
                        accountAp.setBuyReturnAmt(buyrt);
                    }
                    accountAp.setReturnAmt(returnAmt);
                    accountAp.setReturnQty(item.getQty().intValue());
                    if(!StringUtils.isNull(item.getLastUpdDt())){
                        String retDate = this.removeSpecialChar(item.getLastUpdDt());
                        accountAp.setReturnTime(DateUtils.parseDate(retDate));
                        retDate =retDate.substring(0,7);
                        accountAp.setReturnMonthYearDate(retDate);
                    }

                    accountAp.setReturnOrderItemNo(item.getCustReturnOrderItemNo());
                    this.mapper.updateById(accountAp);
                }

                sov.setIsReturn("Y");
                sov.setReturnAmt(returnAmt);
                sov.setReturnQty(item.getQty().intValue());
                sov.setReturnOrderItemNo(item.getCustSalesOrderItemNo());
                this.salesOrderItemmapper.updateById(sov);


                item.setStatus(ReturnOrderStatusEnum.PROCESSED.getValue());
                this.returnOrderItemMapper.updateById(item);
            }else if(sov.getStatus().equals("newRece")||sov.getStatus().equals("acc_failed")){

                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
                item.setImportErrorMesg("原始订单还未结算，请等结算之后处理");
                this.genOperationLog(item,user);
                this.returnOrderItemMapper.updateById(item);
                continue;
            }else if(sov.getStatus().equals("rtApplied")){

            }else{

            }
        }
        return rt;
    }
    /**
     * 获得地区订单总数
     *
     * @return
     */
    @Override
    public AccountingApVo countTodayTotalSale(AccountingApSearchParam params) {
        return this.mapper.countTotalTodaySale(params);
    }
    /**
     * 获得地区采购总数
     *
     * @return
     */
    @Override
    public AccountingApVo countTotalTodayPurchase(AccountingApSearchParam params) {
        return this.mapper.countTotalTodayPurchase(params);
    }

    @Override
    public String exportreportData(AccountingApSearchParam params) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "月度结算报表-"+params.getMonthYear().replace("-", "")+ "-"+DateUtils.getDate("yyyyMMdd")+".xlsx";

        List<AccountingApVo> list = this.mapper.settlementViewMonthly(params);
        try {
            new ExcelExport(null, AccountingApVo.class).setDataList(list).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("结算清单", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }
    @Override
    public String removeSpecialChar(String input){
        Pattern p =null;
        Matcher m = null;;
        String rt = "";



        if(!StringUtils.isNull(input)) {
            p = Pattern.compile("\t");
            m = p.matcher(input);
            rt = m.replaceAll("");

        }




        return rt;
    }
    @Override
    public String exportData(AccountingApSearchParam params) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "结算清单-"+params.getJobDateFr().replace("-", "")+ "-"+DateUtils.getDate("yyyyMMdd")+".xlsx";

        List<AccountingApVo> list = this.findAll(params);
        try {
            new ExcelExport(null, AccountingApVo.class).setDataList(list).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("结算清单", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }
    /**
     * 导入
     * @param data
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public SalesOrder importData(String customerNo, SalesOrderItemVo data, String needOrderYn, UserVo user, int itemNo, int line, CustomerVo customerVo, SalesOrder newSalesOrder) {
        data = this.removeSpecialChar(data);


        if (needOrderYn.equals("No")) {
            SalesOrderItem salesOrderItem = this.addNewItem(newSalesOrder, data, user, itemNo, line);
            return newSalesOrder;
        } else {
            SalesOrder salesOrdernext = this.addNewSalesOrder(data, user, customerVo, line);
            SalesOrderItem salesOrderItem = this.addNewItem(salesOrdernext, data, user, itemNo, line);
            return salesOrdernext;
        }
    }
    @Transactional(readOnly = false)
    @Override
    public SalesOrderItem addNewItem(SalesOrder newSalesOrder, SalesOrderItemVo data, UserVo user, int itemNo, int line){

        SalesOrderItem salesOrderItem = new SalesOrderItem();
        salesOrderItem.setErrorFlag(newSalesOrder.getErrorFlag());
        if(!StringUtils.isNull(newSalesOrder.getErrorCode())){
            salesOrderItem.setErrorCode(newSalesOrder.getErrorCode());
            if(newSalesOrder.getErrorCode().equals("101")){
                salesOrderItem.setErrorFlag("Y");
            }
        }
        String errorMsg = newSalesOrder.getImportErrorMesg();
        String itemErrorMsg = "明细保存：";
        BeanUtils.copyProperties(data, salesOrderItem);
        List<SalesOrderItem> salesOrderItems =this.salesOrderItemmapper.findByCustSalesOrderItemNoAndOrProductSkuCode(data.getCustSalesOrderItemNo(),data.getCustSkuId());

        if(salesOrderItems!=null&&salesOrderItems.size()>0){

            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg("订单已经输入，不可重复输入 ");
            operationLog.setMethod("101");
            operationLog.setLocation(data.getCustSalesOrderNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            if(!StringUtils.isNull(errorMsg)){
                errorMsg =
                        errorMsg.concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                // salesOrderItem.setImportErrorMesg(errorMsg);
                salesOrderItem.setErrorFlag("Y");
            }else{
                // salesOrderItem.setImportErrorMesg(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                errorMsg = "订单已经输入，不可重复输入 ";
                salesOrderItem.setErrorFlag("Y");
            }
            itemErrorMsg = itemErrorMsg.concat(errorMsg);
            salesOrderItem.setErrorCode("101");
            salesOrderItem.setErrorFlag("Y");
        }


        StoreVo storeVo=null;
        if(StringUtils.isNull(data.getStoreId())){

            salesOrderItem.setGenAccFailedReason("店铺数据没有维护 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("601"));
            }else{
                salesOrderItem.setErrorCode("601");
            }
            this.genOperationLog(salesOrderItem,user);
            itemErrorMsg=itemErrorMsg.concat("店铺数据没有维护 ");
        }else{
            String storeCode =this.replaceStoreCode(data.getStoreId());
            storeVo = storeMapper.findByCode(storeCode);
            salesOrderItem.setStoreId(storeCode);
        }
        if(storeVo==null){

            salesOrderItem.setGenAccFailedReason("店铺数据没有维护 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("601"));
            }else{
                salesOrderItem.setErrorCode("601");
            }
            this.genOperationLog(salesOrderItem,user);

            itemErrorMsg=itemErrorMsg.concat("店铺数据没有维护 ");
        }
        salesOrderItem.setSalesOrderNo(newSalesOrder.getSalesOrderNo());
        salesOrderItem.setSalesOrderId(newSalesOrder.getId());
        salesOrderItem.setSalesOrderItemNo(String.valueOf(itemNo));
        salesOrderItem.setCustomerNo(newSalesOrder.getCustomerId());
        salesOrderItem.setCustomerName(newSalesOrder.getCustomerName());
        salesOrderItem.setCustSkuId(data.getCustSkuId());
        salesOrderItem.setCustSpuId(data.getCustSpuId());
        CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),data.getCustSkuId(),newSalesOrder.getCustomerId());
        if(custGoodsMapVo==null){
            custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),"通用",newSalesOrder.getCustomerId());
        }
        if(custGoodsMapVo==null){//映射表内没有

            salesOrderItem.setGenAccFailedReason("商品价格不存在本系统，请先导入商品价格 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("201"));
            }else{
                salesOrderItem.setErrorCode("201");
            }
            this.genOperationLog(salesOrderItem,user);

            itemErrorMsg=itemErrorMsg.concat("商品价格不存在本系统，请先导入商品价格 ");
        }else{
            salesOrderItem.setSpuId(custGoodsMapVo.getSpuId());
            salesOrderItem.setSkuId(custGoodsMapVo.getSkuId());
            salesOrderItem.setMaterialMapId(custGoodsMapVo.getId());

        }

        if(data.getQty()==null){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数为空 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(String.valueOf(data.getQty()).contains(".")){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(data.getQty()<0) {
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");

            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
        if(StringUtils.isNull(data.getCustSpuId())){
            //||StringUtils.isNull(data.getCustSkuId())
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("100"));
            }else{
                salesOrderItem.setErrorCode("100");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg = itemErrorMsg.concat("对方商品ID为空");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }

        List<SalesOrderItemVo> beforesalesOrderItems =new ArrayList<SalesOrderItemVo>();
        if(!StringUtils.isNull(data.getDiscountActivityCode()))
        {

            beforesalesOrderItems =this.salesOrderItemmapper.findBySkuCodeWithActcode(data.getCustSkuId(),data.getDiscountActivityCode());
            if(beforesalesOrderItems!=null&&beforesalesOrderItems.size()>0){
                SalesOrderItemVo bsalesOrderItem = (SalesOrderItemVo)beforesalesOrderItems.get(0);

                Double unitprice = Double.valueOf(data.getCustRelSalesPrice());
                if(!StringUtils.isNull(bsalesOrderItem.getCustRelSalesUnitPrice())){
                    Double oldunitprice = Double.valueOf(bsalesOrderItem.getCustRelSalesUnitPrice());
                    if(!oldunitprice.equals(unitprice)){
                        PriceTrack priceTrack = new PriceTrack();
                        priceTrack.setCity(data.getCustSkuId());
                        priceTrack.setAddress(data.getSkuName());
                        priceTrack.setPhone(data.getCustRelSalesPrice());
                        priceTrack.setName(data.getCustSalesOrderItemNo());
                        if(storeVo!=null){
                            priceTrack.setStoreName(storeVo.getStoreName());
                        }
                        priceTrack.setProvince(data.getOrderTime());
                        priceTrack.setCustSpu(data.getCustSpuId());
                        priceTrack.setUserId(bsalesOrderItem.getCustSalesOrderItemNo());
                        priceTrack.setDistrict(String.valueOf(bsalesOrderItem.getCustRelSalesUnitPrice()));
                        priceTrack.setId(idWorker.nextId() + "").preInsert(user.getId());
                        this.priceTrackmapper.insert(priceTrack);
                    }
                }
            }
        }else{
            List<MaterialBuyPriceVo> materialBuyPriceOrderVos =new ArrayList<MaterialBuyPriceVo>();
            beforesalesOrderItems =new ArrayList<SalesOrderItemVo>();
            materialBuyPriceOrderVos = this.materialBuyPriceMapper.findPriceBySku(data.getCustSkuId());
            if(materialBuyPriceOrderVos!=null&&materialBuyPriceOrderVos.size()>0){
                MaterialBuyPriceVo materialBuyPriceOrderVo
                        = (MaterialBuyPriceVo)materialBuyPriceOrderVos.get(0);
                Double salePrice =  materialBuyPriceOrderVo.getCustSalesPrice();
                Double unitprice = Double.valueOf(data.getCustRelSalesPrice());
                if(!StringUtils.isNull(salePrice)){

                    if(!salePrice.equals(unitprice)){
                        PriceTrack priceTrack = new PriceTrack();
                        priceTrack.setCity(data.getCustSkuId());
                        priceTrack.setAddress(data.getSkuName());
                        priceTrack.setPhone(data.getCustRelSalesPrice());
                        priceTrack.setName(data.getCustSalesOrderItemNo());
                        if(!StringUtils.isNull(materialBuyPriceOrderVo.getRemark())){
                            priceTrack.setUserId(materialBuyPriceOrderVo.getRemark());
                        }else{
                            priceTrack.setUserId("与登记常规价格记录不符");
                        }
                        if(storeVo!=null){
                            priceTrack.setStoreName(storeVo.getStoreName());
                        }
                        priceTrack.setProvince(data.getOrderTime());
                        priceTrack.setCustSpu(data.getCustSpuId());
                        priceTrack.setRemark(materialBuyPriceOrderVo.getSettlePrice());
                        priceTrack.setDistrict(String.valueOf(materialBuyPriceOrderVo.getCustSalesPrice()));
                        priceTrack.setId(idWorker.nextId() + "").preInsert(user.getId());
                        this.priceTrackmapper.insert(priceTrack);
                        MaterialBuyPrice entityFromDb = this.materialBuyPriceMapper.selectById(materialBuyPriceOrderVo.getId());
                        if (entityFromDb == null) {
                            throw new ParamException("id=" + materialBuyPriceOrderVo.getId());
                        }

                        BeanUtils.copyProperties(materialBuyPriceOrderVo, entityFromDb);
                        entityFromDb.setCustSalesPrice(Double.valueOf(data.getCustRelSalesPrice()));
                        entityFromDb.setRemark(data.getCustSalesOrderItemNo());
                        entityFromDb.preUpdate(user.getId());
                        this.materialBuyPriceMapper.updateById(entityFromDb);

                    }// end !oldunitprice.equals(unitprice)
                }else{
                    materialBuyPriceOrderVo.setCustSalesPrice(unitprice);
                    MaterialBuyPrice entityFromDb = this.materialBuyPriceMapper.selectById(materialBuyPriceOrderVo.getId());
                    if (entityFromDb == null) {
                        throw new ParamException("id=" + materialBuyPriceOrderVo.getId());
                    }

                    BeanUtils.copyProperties(materialBuyPriceOrderVo, entityFromDb);
                    entityFromDb.preUpdate(user.getId());
                    this.materialBuyPriceMapper.updateById(entityFromDb);

                    beforesalesOrderItems =this.salesOrderItemmapper.findBySkuCode(data.getCustSkuId());
                    if(beforesalesOrderItems!=null&&beforesalesOrderItems.size()>0){
                        SalesOrderItemVo bsalesOrderItem = (SalesOrderItemVo)beforesalesOrderItems.get(0);

                        unitprice = Double.valueOf(data.getCustRelSalesPrice());
                        if(!StringUtils.isNull(bsalesOrderItem.getCustRelSalesUnitPrice())){
                            Double oldunitprice = Double.valueOf(bsalesOrderItem.getCustRelSalesUnitPrice());
                            if(!oldunitprice.equals(unitprice)){
                                PriceTrack priceTrack = new PriceTrack();
                                priceTrack.setCity(data.getCustSkuId());
                                priceTrack.setAddress(data.getSkuName());
                                priceTrack.setPhone(data.getCustRelSalesPrice());
                                priceTrack.setName(data.getCustSalesOrderItemNo());
                                priceTrack.setRemark(materialBuyPriceOrderVo.getSettlePrice());
                                if(storeVo!=null){
                                    priceTrack.setStoreName(storeVo.getStoreName());
                                }
                                priceTrack.setProvince(data.getOrderTime());
                                priceTrack.setCustSpu(data.getCustSpuId());
                                priceTrack.setUserId(bsalesOrderItem.getCustSalesOrderItemNo());
                                priceTrack.setDistrict(String.valueOf(bsalesOrderItem.getCustRelSalesUnitPrice()));
                                priceTrack.setId(idWorker.nextId() + "").preInsert(user.getId());
                                this.priceTrackmapper.insert(priceTrack);
                            }// end !oldunitprice.equals(unitprice)
                        }// end CustRelSalesUnitPrice not null
                    }//end beforesalesOrderItems null
                }//end else  price null
            }//end  material null
        }// else not activity




        salesOrderItem.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if(StringUtils.isNull(salesOrderItem.getStatus())){
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        }

        salesOrderItem.setOriginalQty(data.getQty());
        if(storeVo!=null){
            salesOrderItem.setSupplierNo(storeVo.getSupplierId());
            salesOrderItem.setSupplierName(storeVo.getSupplierName());
            salesOrderItem.setStoreName(storeVo.getStoreName());
        }else{
            salesOrderItem.setSupplierNo("");
            salesOrderItem.setSupplierName("");
            salesOrderItem.setStoreName("");
        }


        if(StringUtils.isNull(salesOrderItem.getErrorFlag())){
            salesOrderItem.setErrorFlag("N");
        }
        if(!StringUtils.isNull(data.getOrderTime())){
            Date jobdt= DateUtils.parseDate(data.getOrderTime());
            salesOrderItem.setCreateTime(jobdt);
            salesOrderItem.setOrderTime(DateUtils.formatDateTime(jobdt));


        }
        salesOrderItem.setImportErrorMesg(itemErrorMsg);

        try{
            if(!StringUtils.isNull(data.getCustRelSalesPrice())){
                Double price = NumberUtils.mul(data.getQty().doubleValue(),Double.valueOf(data.getCustRelSalesPrice()));
                salesOrderItem.setCustRelSalesPrice(String.valueOf(price));
                salesOrderItem.setCustRelSalesUnitPrice(Double.valueOf(data.getCustRelSalesPrice()));
            }
            salesOrderItem.setCouponDiscount(data.getCouponDiscount());
            salesOrderItem.setMileageCouponDiscount(data.getMileageCouponDiscount());
            salesOrderItem.setSupplierStatus(SalesOrderStatusEnum.CREATED.getValue());
            this.salesOrderItemmapper.insert(salesOrderItem);
        }catch(Exception e){
            log.error("addNewItem error:", e);
            log.error(ToStringBuilder.reflectionToString(data, ToStringStyle.JSON_STYLE));
            salesOrderItem.setImportErrorMesg(e.getMessage().substring(0,49));
            salesOrderItem.setCustSalesOrderNo(String.valueOf(line));
            this.genOperationLog(salesOrderItem,user);
        }


        return salesOrderItem;
    }
    @Transactional(readOnly = false)
    @Override
    public SalesOrder addNewSalesOrder(SalesOrderItemVo salesOrderItemVo,UserVo user,CustomerVo customerVo,int line) {

        SalesOrder salesOrder = new SalesOrder();
        String importError = "";
        String errorFlag="N";
        if(!StringUtils.isNull(salesOrderItemVo.getStoreId())){
            String storeCode =this.replaceStoreCode(salesOrderItemVo.getStoreId());
            StoreVo storeVo = storeMapper.findByCode(storeCode);

            salesOrder.setStoreId(storeCode);
            if(storeVo!=null){
                salesOrder.setStoreId(storeVo.getStoreCode());
            }else{
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
                operationLog.setErrorMsg(salesOrderItemVo.getCustSalesOrderItemNo()+"店铺基础数据没有维护");
                operationLog.setMethod("601");
                operationLog.setLocation("子订单号:".concat(salesOrderItemVo.getCustSalesOrderItemNo()));
                operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);

                importError ="店铺没有查到";
                errorFlag="Y";
            }
        }else{
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(salesOrderItemVo.getCustSalesOrderItemNo()+"店铺基础数据没有提供");
            operationLog.setMethod("601");
            operationLog.setLocation("子订单号:".concat(salesOrderItemVo.getCustSalesOrderItemNo()));

            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            importError ="店铺数据原始订单未提供";
            errorFlag="Y";
        }
        // String orderNo = this.generalSeqService.generateSeq("oms_sales_order");
        salesOrder.setCustSalesOrderNo(salesOrderItemVo.getCustSalesOrderNo());

        salesOrder.setCustomerId(customerVo.getId());
        salesOrder.setCustomerName(customerVo.getCustomerName());
        salesOrder.setDeliveryStatus(salesOrderItemVo.getDeliveryStatus());
        salesOrder.setFreightFee(salesOrderItemVo.getFreightFee());
        salesOrder.setOrderStatus(salesOrderItemVo.getCustOrderStatus());
        salesOrder.setOrderType(SalesOrderTypeEnum.BySku.getValue());
        salesOrder.setPayStatus(salesOrderItemVo.getPaymentStatus());
        salesOrder.setSourceType(SalesOrderSourceEnum.Byexcel.getValue());
        salesOrder.setStoreSource(salesOrderItemVo.getStoreSource());
        salesOrder.setErrorFlag(errorFlag);
        salesOrder.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        salesOrder.setSalesOrderNo(salesOrder.getId());
        this.orderMapper.insert(salesOrder);


        return salesOrder;


    }

    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(SalesOrderItem data,UserVo user ) {
        OperationLog operationLog = new OperationLog();
        if(data.getErrorCode().equals("201")||data.getErrorCode().equals("601")){
            operationLog.setOperationType(ErrorType.ACCPROCESSIMPORT.getStatusName());
        }else{
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        }

        String errormsg = " ";
        if(!StringUtils.isNull(data.getGenAccFailedReason())){
            errormsg = errormsg.concat(data.getGenAccFailedReason());
        }
        if(!StringUtils.isNull(data.getImportErrorMesg())){
            errormsg = errormsg.concat(data.getImportErrorMesg());
        }
        operationLog.setErrorMsg(errormsg);
        operationLog.setMethod(data.getErrorCode());
        String orderNo = "子订单号: ".concat(data.getCustSalesOrderItemNo());
        if(!StringUtils.isNull(data.getCustSpuId())){
            orderNo=orderNo.concat(" SPU: ").concat(data.getCustSpuId());
        }
        if(!StringUtils.isNull(data.getCustSkuId())){
            orderNo=orderNo.concat(" SKU: ").concat(data.getCustSkuId());
        }
        if(!StringUtils.isNull(data.getStoreDiscountActId())){
            orderNo=orderNo.concat(" 店铺活动号: ").concat(data.getStoreDiscountActId());
        }
        if(!StringUtils.isNull(data.getDiscountActivityCode())){
            orderNo=orderNo.concat(" 折扣券号: ").concat(data.getDiscountActivityCode());
        }
        if(!StringUtils.isNull(data.getStoreDiscountActId())){
            orderNo=orderNo.concat(" 折扣活动编号: ").concat(data.getStoreDiscountActId());
        }

        operationLog.setLocation(orderNo);
        operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }
    @Override
    public SalesOrderItemVo removeSpecialChar(SalesOrderItemVo input){
        Pattern p =null;
        Matcher m = null;;
        String rt = "";
        if(StringUtils.isNull(input.getGroupOrSpu())||input.getGroupOrSpu()==""){
            input.setGroupOrSpu("单品");
        }else{
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getGroupOrSpu());
            rt = m.replaceAll("");
            input.setGroupOrSpu(rt);
        }
        if(!StringUtils.isNull(input.getCustSalesOrderNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSalesOrderNo());
            rt = m.replaceAll("");
            input.setCustSalesOrderNo(rt);
        }
        if(!StringUtils.isNull(input.getCustSalesOrderItemNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSalesOrderItemNo());
            rt = m.replaceAll("");
            input.setCustSalesOrderItemNo(rt);
        }

        if(!StringUtils.isNull(input.getStoreName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreName());
            rt = m.replaceAll("");
            input.setStoreName(rt);
        }

        if(!StringUtils.isNull(input.getCustSkuId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSkuId());
            rt = m.replaceAll("");
            input.setCustSkuId(rt);
        }

        if(!StringUtils.isNull(input.getCustSpuId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSpuId());
            rt = m.replaceAll("");
            input.setCustSpuId(rt);
        }

        if(!StringUtils.isNull(input.getSpuName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSpuName());
            rt = m.replaceAll("");
            input.setSpuName(rt);
        }
        if(!StringUtils.isNull(input.getStoreName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreName());
            rt = m.replaceAll("");
            input.setStoreName(rt);
        }
        if(!StringUtils.isNull(input.getSupplierName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSupplierName());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }
        if(!StringUtils.isNull(input.getOrderTime())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getOrderTime());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }
        if(!StringUtils.isNull(input.getCustRelSalesPrice())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustRelSalesPrice());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustRelSalesPrice(rt);
            }else{
                rt = rt.substring(1);
                input.setCustRelSalesPrice(rt);
            }
        }
        if(!StringUtils.isNull(input.getCustCashPaymentAmt())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustCashPaymentAmt());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustCashPaymentAmt(rt);
            }else{
                rt = rt.substring(1);
                input.setCustCashPaymentAmt(rt);
            }


        }
        if(!StringUtils.isNull(input.getCustMilePaymentAmt())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustMilePaymentAmt());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustMilePaymentAmt(rt);
            }else{
                rt = rt.substring(1);
                input.setCustMilePaymentAmt(rt);
            }

        }
        if(!StringUtils.isNull(input.getSkuName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSkuName());
            rt = m.replaceAll("");
            input.setSkuName(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryAddTime())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryAddTime());
            rt = m.replaceAll("");
            input.setDeliveryAddTime(rt);
        }
        if(!StringUtils.isNull(input.getStoreDiscountCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreDiscountCode());
            rt = m.replaceAll("");
            input.setStoreDiscountCode(rt);
        }
        if(!StringUtils.isNull(input.getPaymentStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getPaymentStatus());
            rt = m.replaceAll("");
            input.setPaymentStatus(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryStatus());
            rt = m.replaceAll("");
            input.setDeliveryStatus(rt);
        }
        if(!StringUtils.isNull(input.getCustNote())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustNote());
            rt = m.replaceAll("");
            input.setCustNote(rt);
        }
        if(!StringUtils.isNull(input.getOrderSource())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getOrderSource());
            rt = m.replaceAll("");
            input.setOrderSource(rt);
        }
        if(!StringUtils.isNull(input.getStoreDiscountActId())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreDiscountActId());
            rt = m.replaceAll("");
            input.setStoreDiscountActId(rt);
        }
        if(!StringUtils.isNull(input.getDiscountActivityName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDiscountActivityName());
            rt = m.replaceAll("");
            input.setDiscountActivityName(rt);
        }
        if(!StringUtils.isNull(input.getDiscountActivityCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDiscountActivityCode());
            rt = m.replaceAll("");
            input.setDiscountActivityCode(rt);
        }
        if(!StringUtils.isNull(input.getProductAttribution())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getProductAttribution());
            rt = m.replaceAll("");
            input.setProductAttribution(rt);
        }
        if(!StringUtils.isNull(input.getAfterSaleService())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getAfterSaleService());
            rt = m.replaceAll("");
            input.setAfterSaleService(rt);
        }
        if(!StringUtils.isNull(input.getCustOrderStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustOrderStatus());
            rt = m.replaceAll("");
            input.setCustOrderStatus(rt);
        }
        return input;
    }
    private String replaceStoreCode(String storeCode){
        String rtStore = "贸易";
        if(storeCode.contains("南航贸易")){
            storeCode =storeCode.trim();
            String num = storeCode.substring(4);
            String lastnum = "";
            if(num.length()==1){
                lastnum = "00".concat(num);
            }else if(num.length()==2){
                lastnum = "0".concat(num);
            }else{
                lastnum=num;
            }
            rtStore = rtStore.concat(lastnum);
        }else{
            rtStore = storeCode;
        }
        return rtStore;
    }
}
